How to declare variables immune to clear all?

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.


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


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  

Tags:

Matlab