Using a while loop to perform like cumsum function.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
James Tursa
am 9 Jul. 2015
Bearbeitet: James Tursa
am 9 Jul. 2015
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
am 9 Jul. 2015
Bearbeitet: John D'Errico
am 9 Jul. 2015
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.
Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!