a simple Question about loops

2 Ansichten (letzte 30 Tage)
Rica
Rica am 12 Mär. 2014
Bearbeitet: Rica am 12 Mär. 2014
Hi All
for exemple:
%%
%
a=[1 2 3 5 4 8];
v=[]
v(1)=a(1);
for k=2:length(a)
if(k<3)
v(k)=v(k)*(k-1);
else
v(k)=(v(k-1)+(v(k))/3);
end
end
i get this error: Attempted to access v(2); index out of bounds because numel(v)=1.
why? thanks for yor help

Akzeptierte Antwort

Chris C
Chris C am 12 Mär. 2014
Bearbeitet: Chris C am 12 Mär. 2014
You initialize v incorrectly. Try it this way....
a=[1 2 3 5 4 8];
v=ones(length(a));
v(1)=a(1);
for k=2:length(a)
if(k<3)
v(k)=v(k)*(k-1);
else
v(k)=(v(k-1)+(v(k))/3);
end
end

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by