a simple Question about loops

1 view (last 30 days)
Rica
Rica on 12 Mar 2014
Edited: Rica on 12 Mar 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

Accepted Answer

Chris C
Chris C on 12 Mar 2014
Edited: Chris C on 12 Mar 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

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!