Summation after looping
4 ビュー (過去 30 日間)
古いコメントを表示
I got a problem with summation after looping. Here is the problem :
------------------------------------------
for ri = 0:3
if ri == 0
mi = 1
elseif i > 0
mi = 1
end
end
r = sum(ri)
------------------------------------------
I'm expecting the result from r was 6 (0+1+2+3) but its result was 3. I think the sum command only read the last ri which is 3 and neglecting the other ri.
Any answer will be appreciated. Thanks!
0 件のコメント
採用された回答
Matt Kindig
2012 年 5 月 16 日
When you use the 'for' statement, you iteratively set ri to each of the values 0, 1, 2, 3. Thus ri only contains 3 after the loop. Instead, assign ri=0:3 to a different variable and have the for loop iterate over that.
For example,
rr = 0:3;
for ri=rr,
if ri == 0
mi = 1
elseif i > 0
mi = 1
end
end
r = sum(rr); %this will be 6
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!