MATLAB Answers

incrementation in for loop

98 ビュー (過去 30 日間)
Harel Harel Shattenstein
Harel Harel Shattenstein 2015 年 5 月 12 日
編集済み: Robbin van Hoek 2015 年 5 月 12 日
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?

  0 件のコメント

サインインしてコメントする。

採用された回答

Pratik Bajaria
Pratik Bajaria 2015 年 5 月 12 日
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 件のコメント

Harel Harel Shattenstein
Harel Harel Shattenstein 2015 年 5 月 12 日
I just used the demo code that is written on the "for" loop. I just try to understand what are the why of incremention available
Walter Roberson
Walter Roberson 2015 年 5 月 12 日
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 2015 年 5 月 12 日
I think documentation must solve your problem of understanding the for loop syntax.

サインインしてコメントする。

その他の回答 (2 件)

Torsten
Torsten 2015 年 5 月 12 日

  0 件のコメント

サインインしてコメントする。


Robbin van Hoek
Robbin van Hoek 2015 年 5 月 12 日
編集済み: Robbin van Hoek 2015 年 5 月 12 日
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

  0 件のコメント

サインインしてコメントする。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by