How to get final iteration when using for loops

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 个)

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.

类别

在 帮助中心 和 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!

Translated by