Why iterations cannot be defined before a 'for' loop

조회 수: 3 (최근 30일)
Emma Humphrey
Emma Humphrey 2018년 8월 25일
편집: Stephen23 2018년 8월 26일
Hello everyone,
I'm curious as to why the following For loop code works
for
n = [2 5 8 11 14 ];
a=n+1;
disp(a)
end
But the code here, doesn't. Is it something to do with how the for loop operation is defined?
n = [2 5 8 11 14];
for n ;
a=n+1;
disp(a)
end
  댓글 수: 1
Stephen23
Stephen23 2018년 8월 25일
"Why iterations cannot be defined before a 'for' loop"
They can be, and it is very useful to do so!

댓글을 달려면 로그인하십시오.

답변 (2개)

Stephen23
Stephen23 2018년 8월 25일
편집: Stephen23 2018년 8월 26일
Your first example follows the syntax shown in the for help:
for index = values
The second example does not, because you do not specify the loop iteration variable. It is equivalent to this:
for values
If you want to make the second example work, then you need to follow the syntax given in the MATLAB documentation, which specifies a loop iteration variable:
vec = [2,5,8,11,14];
for n = vec
...
end
Within the for syntax the = sign does not indicate variable allocation as you seem to be trying to use it, it is simply part of the for syntax to indicate the index variable (which your second example was missing).

Walter Roberson
Walter Roberson 2018년 8월 25일
In your second example you have created a vector named n, and then you want to for the content of the variable without mentioning a different variable. If it were permitted then inside the for loop then would the variable n refer to the vector of all values, or would it refer to the current element of the variable?
The syntax of for is
for variable = expression
The expression can be given as a literal vector or it can be a calculation, including possibly just a reference to a variable already created.
You can think of the right hand side always being evaluated as an expression and the result calculated and stored internally before the loop begins. There is, though, an internal optimization in the case a colon list: in that case MATLAB records the endpoints and increment without storing all of the values internally, as a memory optimization.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by