Why iterations cannot be defined before a 'for' loop
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 25 de Ag. de 2018
"Why iterations cannot be defined before a 'for' loop"
They can be, and it is very useful to do so!
Respuestas (2)
Stephen23
el 25 de Ag. de 2018
Editada: Stephen23
el 26 de Ag. de 2018
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).
0 comentarios
Walter Roberson
el 25 de Ag. de 2018
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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!