Output of a for loop into a vector?

6 views (last 30 days)
chris w
chris w on 1 Nov 2017
Edited: KL on 1 Nov 2017
I need to get the output of this for loop that I created
x=[1 8 3 9 0 1];
b=0;
for i=1:length(x)
b=b+x(i);
end
to put the answers b into a vector eg y=[1 9 12 21 21 22]
I cant seem to do it, i feel like i need to add a y=zeros(size(x)) or something similar but nothing seems to work
thanks

Accepted Answer

KL
KL on 1 Nov 2017
Edited: KL on 1 Nov 2017
You could simply use,
b = cumsum(x)
but if you must use a loop then,
x=[1 8 3 9 0 1];
b=zeros(size(x));
for k=1:numel(x)
b(k)=sum(x(1:k));
end

More Answers (0)

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!