for loop index
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
the cyclist
il 25 Lug 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 Commenti
Più risposte (1)
Walter Roberson
il 25 Lug 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 Commenti
Walter Roberson
il 25 Lug 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.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!