MATLAB: Sum Variable Number of Vectors

2019-08-30 05:55发布

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?

2条回答
可以哭但决不认输i
2楼-- · 2019-08-30 06:39

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
查看更多
We Are One
3楼-- · 2019-08-30 06:53

try this:

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

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

查看更多
登录 后发表回答