Why iterations cannot be defined before a 'for' loop

1 次查看(过去 30 天)
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