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

百般思念 提交于 2020-01-10 19:57:28

问题


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?

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!