How to declare variables immune to clear all?

左心房为你撑大大i 提交于 2019-11-27 07:49:03

问题


Is there anyway to declare variables immune to clear all in MatLab? One solution I thought of was saving the variables and reopening them whenever I need them. Can anyone think of a more elegant solution?

EDIT: Let me explain my problem a bit more thouroughly, which I should have done in the first place; sorry for that.

I have to run a few routines using some "black box" intermediate code (some of which may be mex files). It would be good to assume that I cannot dwell into these codes. I could alter some of them, but that would be costly; for example, I don't know where the clear all is happening. I know I may be asking for too much, but you never know.


回答1:


You can't protect individual variables, but you can use mlock to prevent an M-file function or mex function from being cleared, and any persistent variables defined within.

clear all is really a convenience when one is using the Command Window directly or when writing quick scripts. It does a lot more than just clear variables. It's not a substitute for understanding how your code works or using functions to limit variable scope. If you have a large array that is no longer used, you can explicitly tell Matlab to clear it to save memory. I'd bet what you're actually trying to do could be solved by re-thinking the structure of your code.




回答2:


Instead of protecting variables, consider using clearvars with the -except flag. The use of clear all should be avoided anyway, except you really need to clear ALL.

clearvars -except v1 v2 ... clears all variables except for those specified following the -except

This answer/question can give you further inspiration.


Usage:

a = 1;
b = 2;
c = 3;

vars2keep = {'a','b'}
clearvars('-except',vars2keep{:})

or

clearvars -except a b

and who will return:

Your variables are:

a  b  



回答3:


First of all, you should use local variables wherever possible. If someone clears the base workspace it does not matter for these variables:

function yourcode()
x=1
evilblackbox()
%x is still here
disp(x)
end


function evilblackbox()
clear all
end

There is a ugly workaround, but I really recommend not to use it. You will end up with code which requires restarting matlab whenever you exit the debugger at a wrong location, it throws an exception or similar stupid stuff.

function r=crcontainer(field,data)
persistent X
mlock
if exist('data','var')
    X.(field)=data;
end
r=X.(field);
end

To put a variable in it, use crcontainer('name',3), to read it use crcontainer('name')



来源:https://stackoverflow.com/questions/29423576/how-to-declare-variables-immune-to-clear-all

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