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

matlab

Solution

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`.

Problem

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`?

Original source