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

38 views (last 30 days)
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?

Answers (1)

bio lim
bio lim on 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)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!