Nate Parsons
Nate Parsons

Reputation: 14901

Variable length MATLAB arguments read from variable

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?

Upvotes: 3

Views: 1698

Answers (2)

gnovice
gnovice

Reputation: 125854

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).

Upvotes: 10

DrAl
DrAl

Reputation: 72616

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.

Upvotes: 0

Related Questions