How do I get the average of every n rows for every column in a matrix?
    6 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    amoda
 el 30 de Ag. de 2022
  
Hi everyone, 
I have a matrix Mat1 1085x1376, which I need to find the average of every n rows for every column in the matrix. I did found a solution but for a vector, I dont't how to apply it on the matrix.
Example:
Mat1 = [1 2 3; 4 5 6; 7 8 9; 10 11 12]  % 4x3.  Required is the average of every n=2 rows for Mat1. 
% which should be a  Matrix 
SOL = [2.5 3.5 4.5; 8.5 9.5 10.5] % 2x3
For a vector I used to use following code
n = 335; 
Disp1 = nanmean(reshape( [Vector1(:);nan(mod(-numel(Vector1),n),1)],n,[]))
I would be grateful for any help!
0 comentarios
Respuesta aceptada
  David Hill
      
      
 el 30 de Ag. de 2022
        a=randi(100,15,10);
b=[];
n=5;
for k=1:n:size(a,1)-n
  b=[b;mean(a(k:k+n-1,:))];
end
Más respuestas (2)
  Matt J
      
      
 el 30 de Ag. de 2022
        
      Editada: Matt J
      
      
 el 30 de Ag. de 2022
  
      Mat1= [1 2 3; 4 5 6 ; 7 8 9; 10 11 12],
[m,n]=size(Mat1);
rows=2;
SOL=reshape(Mat1, rows,1,[]);
SOL=mean(SOL,1,'omitnan');
SOL=reshape(SOL,[],n)
3 comentarios
  Image Analyst
      
      
 el 30 de Ag. de 2022
        You can do this in only 2 lines of code (not including setup and comments) if you have the Image Processing Toolbox with the blockproc function, which is specifically built for this kind of operation:
%===============================================================================================================================
% Setup: Define input matrix
Mat1 = [1 2 3; 4 5 6; 7 8 9; 10 11 12]  % 4x3.  Required is the average of every n=2 rows for Mat1. 
% which should be a  Matrix 
% SOL = [2.5 3.5 4.5; 8.5 9.5 10.5] % 2x3
%===============================================================================================================================
% Define mean function
meanFilterFunction = @(theBlockStructure) mean(theBlockStructure.data(:));
%===============================================================================================================================
% Take the mean of 2 element by 1 element block.
% Output matrix is a matrix, half as tall as the input matrix, where every
% 2 by 1 block input block is a single value in the output matrix
% that is the mean of the elements in the block.
SOL = blockproc(Mat1, [2, 1], meanFilterFunction)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



