MATLAB: How to move a variable from the global workspace to a local workspace

globallocalMATLABworkspace

I have a global variable that I want to move into the local workspace so I can continue to use it, without changing the value the copy in the global workspace has.

Best Answer

There is no native way to accomplish this, but the function below should move the variable from the global workspace to the workspace from which the function was called.
function moveToLocal( str )
% MOVETOLOCAL Move a variable form the global to the local workspace
% str should be the name of the variable that is already in the global workspace
% that you wish to move to the local workspace of the calling function.
% The variable will still exist in the global workspace but in the local
% workspace of the calling function the variable will be scoped locally
eval(['global ' str]) % bring the variable in from the global workspace
k=eval(str); % fetch the value of the variable from the global workspace
evalin( 'caller', ['clear ' str]); % clear the value from the caller's workspace
assignin( 'caller', str, k); % assign the value into the caller's local workspace