Using a while loop to perform like cumsum function.

조회 수: 5 (최근 30일)
David Hughes
David Hughes 2015년 7월 9일
편집: John D'Errico 2015년 7월 9일
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
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
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 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