0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That works great! I'll be careful in using it though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.