MATLAB Answers

Is there the more elegant way to do this?

3 views (last 30 days)
G A
G A on 28 Jan 2014
Edited: G A on 31 Jan 2014
I would like to call arguments of function from a string or cell array. For example, this code works as I want:
function testarg()
a=1;b=2;c=3;
m='a,b,c';
eval(['myfun(',m,')']);
function myfun(a,b,c)
a
b
c
Is there another way to do this? Say, without using eval ?

  2 Comments

Jos (10584)
Jos (10584) on 29 Jan 2014
Just a tip: whenever you found yourself using eval, you will be 99.999% sure that there is a way to do it some other way without using eval that is:
  • more efficient
  • less error-prone
  • without hideous side-effects
  • easy to code, read and maintain
  • ...
eval(char('chro''&HB@MCNVHSGNTSDU@K &('+1))
G A
G A on 29 Jan 2014
Thanks, Jos. I knew how 'bad' is eval- this matter was intensively discussed here by the community. I just wanted to demonstrate my purpose - it was my desperate try to achieve what I want.:)

Sign in to comment.

Accepted Answer

Matt J
Matt J on 28 Jan 2014
function myfun(varargin)
varargin{:}

  17 Comments

G A
G A on 31 Jan 2014
Hi Matt, I have realized that I am not happy again. I can reformulate my original question: can I bundle the names of variables as an array of strings and use this array when calling my program with the variables assigned to those names?
Matt J
Matt J on 31 Jan 2014
It sounds like you should be assigning your data to struct fields, rather than to individual variables.
S.a=1;
S.b=2;
S.c=3;
Now everything is conveniently bundled in S and you can pass that around to functions as a single argument.
G A
G A on 31 Jan 2014
Thanks, Matt! Now I can rename all my variables myname to S.myname and use them as before within my program and pass to functions as single argument S. Previous solution - to use variables as C{1}, C{2} is not convenient - without names. Originally, I thought there could be a way to pass the names as 'a', 'b', which I could bundle as C={'a','b'}...

Sign in to comment.

More Answers (1)

Amit
Amit on 28 Jan 2014
function testarg()
a=1;b=2;c=3;
abc(a,b,c)
function abc(a,b,c)
a
b
c
This wil ldo just fine.

  4 Comments

Show 1 older comment
G A
G A on 28 Jan 2014
What I want is to collect all arguments of the function to one array m='a,b,c' and call myfun(m) , instead of myfun(a,b,c)
Amit
Amit on 28 Jan 2014
See MAtt's solution. That will do it.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by