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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With