Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a set of an unknown number of arguments to a function in MATLAB? [duplicate]

When you have a function that takes a variable amount of arguments (like ndgrid), how can you pass an arbitrary list of arguments to that function?

For example I want to make it so that sometimes I pass two vectors to ndgrid and get out two matrices, i.e.,

[X1,X2] = ndgrid(x1,x2);

But other times I might have more X's, so I'll want

[X1,X2,X3,X4] = ndgrid(x1,x2,x3,x4)
  1. Is there any kind of structure I can use to store a list of an unknown number of arguments and then just give that list to a function? And,
  2. Is there a way to retrieve all of the outputs from a function, when you don't know how many there will be?
like image 652
rkp Avatar asked Oct 31 '12 20:10

rkp


1 Answers

To pass in a variable number of inputs to an existing function, use cell arrays with expansion, like this:

x = 1:10;
y = randn(size(x));
plotArguments = {'color' 'red' 'linestyle' '-'};
plot(x, y, plotArguments{:});

or

plotArguments = {1:10 randn(1,10)  'color' 'red' 'linestyle' '-'};
plot(plotArguments{:});

You can use the same trick to receive multiple numbers of outputs. The only hard part is remembering the correct notations.

numArgumentsToAccept = 2;
[results{1:numArgumentsToAccept }] = max(randn(100,1));
like image 107
Pursuit Avatar answered Oct 01 '22 22:10

Pursuit