MATLAB Answers

By element average of multiple matrices

424 views (last 30 days)
Bryan
Bryan on 3 Apr 2012
Commented: Belinda Finlay on 17 Feb 2020
Hi,
I have 40 matrices of 781x981 in dimension. I need to calculate the by element mean of all these matrices in a new, 41st matrix.
I.e., the mean of element 1,1 of all 40 matrices is returned as element 1,1 in the new, 41st matrix. The same is then done for all elements.
In additionto the mean, I need to do the same for the standard deviation also.
Is there a function in Matlab that can do this? Or do I have to write some kind of a loop??
Thanks, Bryan

  0 Comments

Sign in to comment.

Accepted Answer

Wayne King
Wayne King on 3 Apr 2012
Yes, concatenate the matrices into a 3-D array and use mean(x,3)
x = randn(4,4,10);
mean(x,3)
and
std(x,[],3)
To concatenate, you can use cat()
x = randn(4,4);
y = randn(4,4);
z = cat(3,x,y);
mean(z,3)
std(z,[],3)

  1 Comment

Jan
Jan on 3 Apr 2012
... and std(x, 0, 3);

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 3 Apr 2012
Stack your 40 matrices into one three-dimensional matrix, then take the mean along the 3rd dimension
meanMatrix = mean(stackedMatrix,3); %doc mean for more info.
To stack your matrices look at these two FAQs:

  3 Comments

Jan
Jan on 3 Apr 2012
It would be even better to avoid something like A1, A2, ... but store all matrices in a 3D array directly, or at least in a cell. Example:
C = cell(1, 10);
for i=1:10; C{i} = rand(4, 4); end
D = cat(3, C{:});
Bryan
Bryan on 3 Apr 2012
thank you all for your answers, i did not think of this approach
Belinda Finlay
Belinda Finlay on 17 Feb 2020
I am very new to MATLAB and am attempting a do a similar calacuation; however, I am having trouble stacking my matrices (as suggested by Sean), is someone able to guide me.
Thanks
Belinda

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by