필터 지우기
필터 지우기

for loop index

조회 수: 7 (최근 30일)
Mike
Mike 2011년 7월 25일
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

채택된 답변

the cyclist
the cyclist 2011년 7월 25일
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
Mike
Mike 2011년 7월 25일
The 'Keep' command you suggested looks really helpful. Thanks.
Oleg Komarov
Oleg Komarov 2011년 7월 25일
Or clearvars -except var1 var2

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 7월 25일
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
Mike
Mike 2011년 7월 25일
I am a little cursious about the internal memory you just said. Are you saying, like, it is the memory space where matlab stores data, but users have no access to? Is restart the only way to free that memory?
Thanks.
Walter Roberson
Walter Roberson 2011년 7월 25일
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.

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

카테고리

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