How to sum over indexed arrays
Show older comments
I have 3 arrays of the same dimension, having the same name but with indexes. How can one sum over the elements.
clear all; close all;
It=3; %Number of created arrays
for ii=1:It
a(ii) = [1 1 rand()]
end
abc = zeros(size(a(1))); %array abc has zero entries of same dimension as the a-arrays
for ii = 1:It %summation over a-arrays
abc = abc + a(ii)
end
abc %final array with summed elements
What is wrong with it?
7 Comments
Lucius
on 23 May 2015
Walter Roberson
on 23 May 2015
When you have
a(ii) = something
and ii is a scalar value, then the "something" must be exactly one element long. You cannot store a vector as a matrix element. The closest you can get to that is to create a cell from the vector, and then store the cell in the array:
a(ii) = {[1 1 rand()]};
stores the single cell into a(ii). Another way of writing the same thing is
a{ii} = [1 1 rand()];
Notice the use of {} instead of (). You can refer to the content as a{ii} in statements such as
abc = abc + a{ii};
However... your code would be a lot more efficient if you stored everything in a big matrix and used sum() over the appropriate dimension of the matrix.
for ii = 1 : 3
aa(ii,:) = [1 1 rand()];
end
sum(aa,1) %adds the three rows
Lucius
on 23 May 2015
Lucius
on 23 May 2015
Walter Roberson
on 23 May 2015
When enough memory exists, to calculate sum() or mean() or std() or var() or the like, cat() on a dimension one higher than the number of dimensions of the array, and then apply the function along that same dimension number. For example,
mean( cat(4, A1, A2, A3, A4, A5), 4)
Likewise:
numfile = 7;
imgs = zeros(1957, 1957, 3, numfile);
for K = 1 : numfile
imgs(:,:,:,K) = imread(sprintf('image_%04d.jpg', K));
end
meanimg = mean(imgs,4);
Lucius
on 24 May 2015
Answers (1)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!