Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

matlab - How to declare variables immune to clear all?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...