for loop index
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I've got a tricky question. If we run the following script
for ii=1:10
clear all
disp('i')
end
We can see 10 i's printed out in the command window, although the index ii has already been cleared (matlab will tell you it is an undefined variable if you add ii line within the loop). This means matlab can remember the number of loops in some implicit form even when the whole workspace has been cleared, including the loop index itself.
My question is, is there any way to retrieve the loop index after the workspace being cleared. The script to do this should be something like the following, and won't give an error msg of "undefined variable ii":
for ii=1:10
clear all
...
...
ii
end
0 comentarios
Respuesta aceptada
the cyclist
el 25 de Jul. de 2011
I have to admit I have no idea how to do that, and I am extremely curious why you would want the clear all in there in the first place.
You might be interested in the "keep" command from the File Exchange:
4 comentarios
Más respuestas (1)
Walter Roberson
el 25 de Jul. de 2011
No, there is no provided mechanism for that.
The loop index value is held in internal memory, and the statement is executed as if the loop variable is initialized to the current value at the top of the loop. When you "clear all", you lose access to the loop variable, but the internal value is not disturbed.
2 comentarios
Walter Roberson
el 25 de Jul. de 2011
Yes, it is internal memory where MATLAB stores data but users have no access to. MATLAB manages it automatically. To free the memory, terminate the "for" loop.
You should not be surprised that MATLAB manages memory that it does not give users access to. Consider, for example, that MATLAB must manage the call stack -- the information about exactly where the present routine was called from -- so that after this routine exits, the previous routine can resume execution. MATLAB is not going to allow the user to overwrite or release that memory.
MATLAB is not a compiler; internally it works as an interpreter. It uses whatever internal state it needs.
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!