incrementation in for loop
조회 수: 7 (최근 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!