incrementation in for loop

27 Ansichten (letzte 30 Tage)
Harel Harel Shattenstein
Harel Harel Shattenstein am 12 Mai 2015
Bearbeitet: Robbin van Hoek am 12 Mai 2015
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?

Akzeptierte Antwort

Pratik Bajaria
Pratik Bajaria am 12 Mai 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 Kommentare
Walter Roberson
Walter Roberson am 12 Mai 2015
Any change you make to the loop control variable within the loop will get overwritten when the next iteration is done. Also, no increment will be done if the last iteration was already executed, so the loop control variable will be left at its value as of the last iteration.
Pratik Bajaria
Pratik Bajaria am 12 Mai 2015
I think documentation must solve your problem of understanding the for loop syntax.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Torsten
Torsten am 12 Mai 2015

Robbin van Hoek
Robbin van Hoek am 12 Mai 2015
Bearbeitet: Robbin van Hoek am 12 Mai 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

Kategorien

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by