Calculating Mean of Matrices
6 views (last 30 days)
Show older comments
I am new to Matlab. I would like to calculate mean of many matrices(about 550 matrices. They are all the same size). I've named them loc1, loc2, loc3 .......loc549, loc550. Please help. Thanks!
4 Comments
Oleg Komarov
on 31 Jul 2012
Edited: Oleg Komarov
on 31 Jul 2012
I think you're missing the point, "evaling" variables is not a good approach. You will find yourself stuck in the eval paradigm forever.
Try the other methods suggested in the FAQ that per isakson posted.
Oleg Komarov
on 31 Jul 2012
Sorry but 500x1 are vectors, not matrices and their row-means are equal to the values itselves.
Answers (3)
per isakson
on 31 Jul 2012
Edited: per isakson
on 31 Jul 2012
It was probably not a good idea to name them "loc1, loc2, loc3 .......loc549, loc550". See How can I create variables A1, A2,...,A10 in a loop?.
However,
mean(loc1(:))
returns the mean of a numerical array.
Please, have a look at the Getting Started.
5 Comments
E K
on 31 Jul 2012
try to use a cell structure with each cell element got one of your matrix then you can call them like C{1,1}
and with a for loop it will be very easy to find the mean of them.
per isakson
on 31 Jul 2012
@John
- you did not read the FAQ-entry, "A1,A2...", carefully enough
- read the documentation on MEAN
Oleg Komarov
on 31 Jul 2012
Then create one array loc, which will have the usual n by m dimension but you will be adding slices in a loop on the third dimension.
An example, suppose you are importing data (but I will be generating it):
% preallocate
A = zeros(2,4,10); % You know you will have 10 matrices
for ii = 1:10
A(:,:,ii) = rand(2,4); % one matrix per slice
end
Try to apply this example to your case, then you just have to use
mean(A,2)
mean along rows.
0 Comments
Azzi Abdelmalek
on 31 Jul 2012
Edited: Azzi Abdelmalek
on 1 Aug 2012
for k=1:550
mat=sprintf('loc%d',k);result1=sprintf('result(%d,:)',k)
%eval([mat '=rand(2,2)']) %it's just an exemple for testing
eval([result1 '=mean(' mat ,')'])
end
% the variable result is an array with 550 lines ;each line corresponds to the mean of each matrix
5 Comments
Azzi Abdelmalek
on 1 Aug 2012
Edited: Azzi Abdelmalek
on 12 Sep 2012
M Komarov result1 is not overwritten, result1=sprintf('result(%d)',k) when k=2; result1='result(2)'. maby i didn't read all the question, I will remove one "mean'
Oleg Komarov
on 1 Aug 2012
Ok, I agree. But, I think it is a very unhappy choice to call it result1 and assign it a dynamic string and then eval it.
Other methods are much clearer and less prone to errors.
See Also
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!