如何将一组未知数量的参数传递给 MATLAB 中的函数? [英] How can I pass a set of an unknown number of arguments to a function in MATLAB?
问题描述
当您有一个接受可变数量参数的函数(如 ndgrid)时,您如何将任意参数列表传递给该函数?
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?
例如我想让它有时我将两个向量传递给 ndgrid 并得到两个矩阵,即,
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);
但有时我可能有更多的 X,所以我会想要
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{:});
或
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));
这篇关于如何将一组未知数量的参数传递给 MATLAB 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!