views:

614

answers:

2

I have a function with variable arguments, declared in the standard way:

[] = foo ( varargin )

and I would like to call it from another function, but specify the arguments programmatically. My best attempt is something like the following:

% bar isn't populated like this, but this is how it ends up
bar = { 'var1' 'var2' 'var3' }; 
foo( bar );

However, bar is put into a 1x1 cell array, and not interpreted as a 1x3 cell array as I intended. I can't change foo, so is there a workaround?

+9  A: 

If you have variables a, b, and c that you want to collect together somewhere and ultimately pass to a function as a series of inputs, you can do the following:

inArgs = {a b c};  % Put values in a cell array
foo(inArgs{:});

The syntax inArgs{:} extracts all the values from the cell array as a comma-separated list. The above is therefore equivalent to this:

foo(a,b,c);

If foo is written to accept a variable-length argument list, then the varargin variable will end up being a 1-by-3 cell array where each element stores a separate input argument. Basically, varargin will look exactly like the variable inArgs. If your call to foo didn't use the {:} operator:

foo(inArgs);

then the varargin variable would be a 1-by-1 cell array where the first element is itself the cell array inArgs. In other words, foo would have only 1 input (a 1-by-3 cell array).

gnovice
A: 

The only way that I'm aware of is to use eval, however I don't have MATLAB here, so I can't check the syntax correctly.

If you coerce the bar into a string of the form "'var1', 'var2', 'var3'", you can do:

eval(["foo(", barString, ")"])

Hope that gets you going and sorry it isn't a comprehensive answer.

Al
the {:} syntax looks better though!
Al
Note that in addition to being very slow, eval has some weird semantics in recent versions of Matlab where it can sometimes confuse variable names and function names. Here's one person who ran into the gotcha: http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/237730
Mr Fooz