MATLAB Answers

Mean of rows and columns of several matrices in a cell

8 views (last 30 days)
rihab on 8 Sep 2015
Edited: Stephen on 8 Sep 2015
I have say 'n' axb matrices and i want to generate a new matrix of dimension axb which is the mean of all 'n' axb matrices, i.e the first element of this new matrix is the mean of all first elements in each 'n' axb matrices and so on. Is there a way to compute this average matrix from a group of matrices in matlab? I had tried to do this by creating a cell but couldn't figure out how to take mean of each element of these matrices. I would appreciate any ideas or suggestions.
Thank you!

Accepted Answer

Stephen on 8 Sep 2015
Edited: Stephen on 8 Sep 2015
MATLAB is fastest and easiest when you stick with using numeric arrays and learn how to use the dimensions of the arrays, rather than sticking data in complicated data classes like cell arrays and structures. (most importantly this includes learning how to write vectorized code). If you use the third dimension of an array then your problem is easy using mean:
>> X(:,:,3) = [1,2;3,4];
>> X(:,:,2) = [5,6;7,8];
>> X(:,:,1) = [9,0;1,2];
>> mean(X,3)
ans =
5.0000 2.6667
3.6667 4.6667
The best solution is to create your n matrices in this single numeric array. The second best solution is to create your arrays inside a cell array, which can then be concatenated together like this:
>> Y{3} = [1,2;3,4];
>> Y{2} = [5,6;7,8];
>> Y{1} = [9,0;1,2];
>> X = cat(3,Y{:})
>> mean(X,3)
You will find that the X is the same as in the first example.
The one method you should not use is to dynamically create the n matrices as individual variables (e.g. sequentially numbered) and then attempt to join them together: creating variable names dynamically is buggy, slow and a very poor programming practice.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!