HappyPy
HappyPy

Reputation: 10697

assign values to variable names in Matlab

Is there a way to assign values to variable names which are both supplied by the user?

I thought of something along these lines:

function varargout=my_fun(varargin)

for i=1:2:nargin
eval('varargin{i}=varargin{i+1}')
end

>> my_fun('a',1,'b',2)

>> a

1

>> b

2

but it doesn't work.

Upvotes: 0

Views: 191

Answers (1)

Daniel
Daniel

Reputation: 36710

You could do this using assignin, but I strongly recommend not to use such solution. It violates the common expectations of a variable scope. Besides this, assignin and eval are two of the best option to confuse the matlab editor, which results in many useless recommendations and warnings.

If you really need such a solution:

assignin('caller',varargin{i},varargin{i+1}) to assign to the caller work space.

Upvotes: 1

Related Questions