How to remove the variable “clear” in MATLAB

£可爱£侵袭症+ 提交于 2019-11-30 08:54:10

问题


Let's say you are some new programmer and you do something like...

%...la da da
%...programming away
if such && such
    clear = 1;
else 
    clear = 0;
end 

or in some other way, you assign the variable clear a value.

Is there some way to "clear" clear?

clearvars doesn't work. Clicking the workspace variable and manually clicking delete does work, but I think it's cheating.


回答1:


This will do it:

builtin('clear','clear')

Note: Keep in mind to avoid such operations to keep code clarity. Only do overwrite when it is the exact action you want to take place. Otherwise it may cause future bugs if you forgot (or if another person uses your code and didn't realize it) that you have the clear (or any other) function overwritten. You could easily name this variable as doClear for example.




回答2:


Any name, even builtin and feval can be overriden. In such case, you can use function handles instead to force MALTAB into interpreting a statement as a function call:

clear = str2func('clear');
clear('clear')

Obviously, str2func can also be overrriden! :) however, there exists a similar solution (inspired by Loren's article), which is creating a separate m-file that does the same thing:

function clearclear()
    assignin('caller', 'clear', @clear);

Calling this function in the main workspace should allow you to do clear('clear') safely.

The second solution takes advantage of the fact that the m-file doesn't "see" the variable clear in the main workspace, and therefore can access the actual handle of the clear function properly.




回答3:


A non intuitive way is

clear = rand(1000,500,700);
pack

This produces the following warning:

Warning: Variable 'clear' cannot be saved to a MAT-file whose version is older than 7.3. To save this variable, use the -v7.3 switch. Skipping...

It also suffers from the same issue that you can assign pack to be a variable.




回答4:


Interesting problem! I found it surprisingly hard to find an ways to do this programatically (besides the one suggested by @TryHard)

Here is the I have come up with though it is a bit more powerfull than clear:

!matlab &
exit

Note that if you want to type this in the command line at once, you need to use a shift+enter in between.



来源:https://stackoverflow.com/questions/18360624/how-to-remove-the-variable-clear-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!