MATLAB: Sum Variable Number of Vectors

2019-08-30 06:33发布

问题:

I have to sum multiple vectors, but their number varies.

I have:

g1 = [1 3 4 5 3 4 6 2 3 4 6 6]
g2 = ....  
.
.
.
gn = [3 4 5 6 4 5 6 2 4 7 8 9]

And I have to sum all of them:

G=sum(g1 to gn)

How do I do that?

回答1:

It would me much easier if you stored all your vectors in a matrix g, one vector in each row. Then the desired result would be simply sum(g).

If you really need to have each vector in a different variable, you can compute the sum with eval within a loop:

result = zeros(size(g1)); % initialize sum
for ii = 1:n
  eval(['result = result + g' num2str(ii) ';']) % add ii-th vector to the sum
end


回答2:

try this:

sum(arrayfun(@(i) eval(['g' num2str(i)]),1:n))

(sums all scalars with name pattern gX, where X=1...n)