Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a workspace variable that persists across a call to clear?

Tags:

matlab

Suppose I run a script X.m and it creates a bunch of variables, and I want to save a variable called Z, so I write myVar = Z.

I then type clear at the prompt, and run Y.m.

Is there a way I can make it so that myVar does not disappear with all the other variables when I call clear?

like image 832
merlin2011 Avatar asked Mar 22 '13 07:03

merlin2011


People also ask

Do workspace variables persist after you exit MATLAB?

Workspace variables do not persist after you exit MATLAB. To use your data across multiple sessions, save it to a compressed file with a . mat extension called a MAT-file. You can restore saved data by loading a MAT-file back into MATLAB.

How do you clear workspace variables in MATLAB?

To clear all variables from the current workspace, use clear or clearvars . To clear all global variables, use clear global or clearvars –global . To clear a particular class, use clear myClass . To clear a particular function or script, use clear functionName .

How do you clear all but one variable in MATLAB?

clearvars -except keepVariables removes all variables, except for those specified by keepVariables . Use this syntax to keep specific variables and remove all others. clearvars variables -except keepVariables removes the variables specified by variables , and does not remove the variables specified by keepVariables .


Video Answer


2 Answers

You can use clearvars to clear all variables except specific ones from workspace. From clearvars documentation:

clearvars -except v1 v2 ... clears all variables except for those specified following the -except flag. Use the wildcard character '' in a variable name to exclude variables that match a pattern from being cleared. clearvars -except X clears all the variables in the current workspace, except for those that start with X, for instance. Use clearvars -except to keep the variables you want and remove all others.

So, you need to type

clearvars -except myVars

instead of clear.

like image 177
HebeleHododo Avatar answered Nov 16 '22 00:11

HebeleHododo


There's Keep on the MATLAB file exchange which lets you clear everything except certain variables that you wish to keep.

like image 22
Edric Avatar answered Nov 16 '22 00:11

Edric