フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by