How do I get the average of every n rows for every column in a matrix?
34 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
David Hill
on 30 Aug 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
More Answers (2)
Matt J
on 30 Aug 2022
Edited: Matt J
on 30 Aug 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)
Image Analyst
on 30 Aug 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)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!