MATLAB Answers

incrementation in for loop

36 views (last 30 days)
x = ones(1,10);
for n = 2:6
x(n) = 2 * x(n - 1);
end
When written as above n increase by 1 after execution of all the code until end? Is there an option to set the incrementation wherever I would like in the code?

Accepted Answer

Pratik Bajaria
Pratik Bajaria on 12 May 2015
Hello,
Its difficult to understand your question, but if you would elaborate it would be great. Although, i would provide solution as per what i have interpreted.
1. It seems you want to store the values at different indexes, rather than in succession. Or 2. It seems you want to change the steps of progression.
In the above cases, solutions could be as follows... 1. define a dummy variable, say pos (as in "position") and at the end of every loop increment as per your requirement. Or 2. while defining the for loop, define the step as: "for i=start:stepsize:end"
In case i haven't interpreted the question properly, i would like you to elaborate it as per the requirement.
Hope it helps.
Regards, Pratik
  3 Comments
Pratik Bajaria
Pratik Bajaria on 12 May 2015
I think documentation must solve your problem of understanding the for loop syntax.

Sign in to comment.

More Answers (2)


Robbin van Hoek
Robbin van Hoek on 12 May 2015
Edited: Robbin van Hoek on 12 May 2015
The way i understand is you want to use a while loop actually.
>> x = ones(1,10);
n=2;
while n < length(x)
x(n) = 2 * x(n - 1);
%for example
n=round(n*1.5);
end
>> x
x =
1 2 4 1 2 1 1 2 1 1
here it will use n=2,3,5,8, and finally 12, which will cause the loop to end.
if you want to use constant spacing or any predefined indexes you can just state that n should be the values in this array (in example the array [2,4,6] is used but you could also say n=[1,2,5,3,6,8] or anything else you like)
>> x = ones(1,10);
for n = 2:2:6
x(n) = 2 * x(n - 1);
end
>> x
x =
1 2 1 2 1 2 1 1 1 1

Tags

Community Treasure Hunt

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

Start Hunting!