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

 Réponse acceptée

KL
KL le 1 Nov 2017
Modifié(e) : KL le 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by