incrementation in for loop
28 次查看(过去 30 天)
显示 更早的评论
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
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 个评论
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
2015-5-12
I think documentation must solve your problem of understanding the for loop syntax.
更多回答(2 个)
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!