I need to add numbers in an array using a for loop...plz help

38 Ansichten (letzte 30 Tage)
Brian C
Brian C am 12 Nov. 2015
Beantwortet: bio lim am 12 Nov. 2015
Say i have array of [1;2;3] and want to sum it, the answer should be 6. im not allow to use Matlab sum function to get the sum ex. sum(A)
Here's what I have
A=[1;2;3]; b=length(A);
sum=0; for i=1:b
sum= sum+i;
end
disp(sum)
Not sure if i am going about this the wrong way. believe my sum=sum+i line is the issue?

Antworten (1)

bio lim
bio lim am 12 Nov. 2015
The problem with your code is sum = sum + i. Your i is defined as i = 1:b = 1:length(A). You are summing the index numbers of your column vector rather than the element of each row. In order words, no matter what element you define in your column vector, as long as the size is maintained (in your case, 3), you will always get the same answer 6. What you need to do is define sum = sum + A(i).
A=[1;2;3]; b=length(A);
sum=0; for i=1:b
sum= sum+A(i);
end
disp(sum)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by