Using a while loop to perform like cumsum function.
5 ビュー (過去 30 日間)
古いコメントを表示
I have to create a code utilizing nested while loops to perform the same operation as cumsum. If I enter A=[1 2 3;4 5 6;7 8 9], the cumsum(A)=[1 2 3;5 7 9;12 15 18]. I don't know where to start. Any help is appreciated.
2 件のコメント
James Tursa
2015 年 7 月 9 日
編集済み: James Tursa
2015 年 7 月 9 日
Make a file, e.g. my_cumsum.m, and start writing code. E.g.,
function y = my_cumsum(x)
y = some initialization code to get the correct size of the output
% then insert your loops here
end
Did your instructions specifically state "nested while loops" or just "nested loops"?
John D'Errico
2015 年 7 月 9 日
編集済み: John D'Errico
2015 年 7 月 9 日
I have no idea why one would want to use a while loop to do this. A for loop seems far more reasonable. But homework assignments are often irrational.
If you INSIST on the use of nested while loops, then this will fit your needs, though it may be less than helpful. :)
n = size(A,1);
while 1
while 1
B = tril(ones(n))*A;
break
end
break
end
B
B =
1 2 3
5 7 9
12 15 18
Since this solution is probably not what your teacher is looking for, why not make an effort? To be honest, I'd suggest writing it using a set of nested FOR loops. Then see how you would need to change that to use while loops instead. While and for loops can indeed be used in exchange of each other, once you think about it.
So I'll make an offer to you. IF you are willing to write it using for loops, and post that, then I'll show you how to convert it to a pair of while loops.
回答 (0 件)
参考
カテゴリ
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!