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
?
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.
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 .
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 .
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
.
There's Keep on the MATLAB file exchange which lets you clear everything except certain variables that you wish to keep.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With