问题
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)
- 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,
- Is there a way to retrieve all of the outputs from a function, when you don't know how many there will be?
回答1:
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));
回答2:
Using varargin
,nargin
, varargout
and nargout
you can easily define variable argument/output functions. See the attached MATLAB documentation link for the varargin page. The others are linked at the bottom:
http://www.mathworks.com/help/matlab/ref/varargin.html
EDIT: BTW, not to toot my own horn, but it seems to be implemented just as I had suggested in the "quick-and-dirty" comment hehehe
回答3:
a function that returns all arguments as outputs:
function varargout = ndgrid(varargin)
varargout = varargin;
return
来源:https://stackoverflow.com/questions/13166961/how-can-i-pass-a-set-of-an-unknown-number-of-arguments-to-a-function-in-matlab