本文介绍了MATLAB:向量的可变数目之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须对多个向量求和,但是它们的数量有所不同.
I have to sum multiple vectors, but their number varies.
我有:
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]
我必须总结所有这些:
G=sum(g1 to gn)
我该怎么做?
推荐答案
如果将所有向量存储在矩阵g
中,每行一个向量,这将使我容易得多.那么所需的结果将只是sum(g)
.
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)
.
如果确实需要将每个向量包含在不同的变量中,则可以在循环中使用eval
计算总和:
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
这篇关于MATLAB:向量的可变数目之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!