Sum of elements with a loop

时间:2018-05-13 22:03:15

标签: matlab

I have to calculate the sum of a vector

v = [5 2 6 8 1 2];

by using a loop. I have tried this

v = [5 2 6 8 1 2];
i = 0;

for i = 1:6
v1 = sum(v(i)) 
i = i + 1;
end

But I cant get it to work. It to choose the first vector and then add it to the second.

1 个答案:

答案 0 :(得分:1)

v = [5 2 6 8 1 2];
sumValue = 0;
for vals = 1:length(v)
    sumValue = sumValue + v(vals);
end
disp(sumValue)