필터 지우기
필터 지우기

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

조회 수: 19 (최근 30일)
Brian C
Brian C 2015년 11월 12일
답변: bio lim 2015년 11월 12일
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?

답변 (1개)

bio lim
bio lim 2015년 11월 12일
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)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by