How to get final iteration when using for loops
Show older comments
I am having trouble displaying the final iteration of my cumsum hardcode. here it is. Thanks
if true
% code
end
x=randi(10,1,10)
n=0;
cumu=0;
for n=1:length(x);
cumu=x(n)+cumu;
x(n)=cumu
end
1 Comment
Antonio Aguirre
on 9 Dec 2017
What specifically do you want to display on the last iteration?
Answers (1)
Star Strider
on 9 Dec 2017
Your code as written (adding an end that you omitted) will do what you want:
x=randi(10,1,10);
n=0;
cumu=0;
for n=1:length(x)
cumu=x(n)+cumu;
end
x(n)=cumu
The final value of ‘n’ will remain defined after the loop, so ‘x(n)’ will be (in your code here) ‘x(10)’.
Also, just writing:
cumu
after the loop will do the same.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!