MATLAB: How to load many variables form base environment

code smellevalinload

Dear reader,
Here is a toy example. Inside a user-defined function, I currently use the following syntax:
a = evalin('base', 'a');
b = evalin('base', 'b');
c = evalin('base', 'c');
which allows me to load 3 matlab variables, called a,b,c from base environment into the current function's workspace. In reality I have many more variables, not only 3. Therefore, I am looking for a more elegant way to write this code.
A solution would be to write a new matlab function (I'll call it loadVarsFromBaseEnv.m) which should permit me to call it as follows:
loadVarsFromBaseEnv a b c
However, I have no idea how to write the code of loadVarsFromBaseEnv.m
Any help, suggestion are highly appreciated.

Best Answer

"goal is not to write nice matlab code, but instead structure it in the most convenient way" &nbsp How come you believe there is conflict between "nice" and "convenient"? Whatever these words mean in this context.
Here is an "elegant" code that meets your original requirements. Example of use:
a = 1;
b = magic(3);
c = dir;
JustGetTheWorkDone a b c
prints
Name Size Bytes Class Attributes
a 1x1 8 double
b 3x3 72 double
c 89x1 57407 struct
varargin 1x3 342 cell
where
function JustGetTheWorkDone( varargin )
loadVarsFromBaseEnv( varargin{:} )
whos
end
and
function loadVarsFromBaseEnv( varargin )
try
for jj = 1 : length( varargin )
val = evalin( 'base', varargin{jj} );
assignin( 'caller', varargin{jj}, val )
end
catch
fprintf( 2, 'loadVarsFromBaseEnv: Something went wrong\n' ) %#ok<PRTCAL>
end
end