How to declare variables immune to clear all?

旧城冷巷雨未停 提交于 2019-11-28 13:28:20

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.

thewaywewalk

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  

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')

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