主要内容

varargin

可变长度输入参数列表

Syntax

Description

example

vararginis an input variable in a function definition statement that enables the function to accept any number of input arguments. Specifyvararginusing lowercase characters, and include it as the last input argument after any explicitly declared inputs.

When the function executes,vararginis a 1-by-Ncell array, whereNis the number of inputs that the function receives after the explicitly declared inputs. However, if the function receives no inputs after the explicitly declared inputs, thenvararginis an empty cell array.

Examples

expand all

在名为的文件中定义函数acceptVariableNumInputs.m这接受可变数量的输入并显示每个输入的值。

typeacceptVariableNumInputs
function acceptVariableNumInputs(varargin) disp("Number of input arguments: " + nargin) celldisp(varargin) end

使用多个输入调用功能。

Appactvariablenuminputs(一个(3),“一些文字”,pi)
Number of input arguments: 3 varargin{1} = 1 1 1 1 1 1 1 1 1 varargin{2} = some text varargin{3} = 3.1416

在名为的文件中定义函数definedAndVariableNumInputs.mthat expects two inputs and accepts an additional number of inputs.

typedefinedAndVariableNumInputs
函数定义andVariaiblenumInputs(x,y,varargin)disp(“输入参数的总数:“ + nargin)Formatspec =“ varargin单元格数组的大小:%dx%d”;str = compose(FormatsPec,size(varargin));disp(str)端

使用多个输入调用功能。

definedAndVariableNumInputs(7,pi,rand(4),datetime('now'),'hello')
Total number of input arguments: 5 Size of varargin cell array: 1x3

Call the function with two inputs.vararginis an empty cell array.

定义和瓦里亚布伦云(13,42)
Total number of input arguments: 2 Size of varargin cell array: 0x0

在名为的文件中定义函数variablenuminputandoutput。m这接受变量数量的输入和输出。

typevariablenuminputandoutput
function varargout = variableNumInputAndOutput(varargin) disp(['Number of provided inputs: ' num2str(length(varargin))]) disp(['Number of requested outputs: ' num2str(nargout)]) for k = 1:nargout varargout{k} = k; end end

用两个输入和三个输出调用该功能。

[d,g,p] = variableNumInputAndOutput(6,'Nexus')
提供输入的数量:2个请求的输出数:3
d = 1
g = 2
p = 3

Call the function again with no inputs or outputs.

variablenuminputandoutput
提供的输入数:0请求的输出数:0

在工作文件夹中的文件中,为绘制红线的绘图函数创建包装器。这redplotfunction accepts a variable-length input argument list and returns a variable-length output argument list. It sets the line color to red, and forwards other input values to theplotfunction. This function wrapper enables you to passredplotthe same inputs asplotand not specify that the line color is red.

typeredplot.m
function varargout = redplot(varargin) [varargout{1:nargout}] = plot(varargin{:},'Color',[1,0,0]); end

Useredplot创建线路图。

x = 0:pi/100:2*pi; y = sin(x); redplot(x,y)

Figure contains an axes object. The axes object contains an object of type line.

Callredplotagain, and specify input and output arguments to forward to theplotfunction.

h = redplot(x,y,“标记”,'o',“标记为彩色”,'green');

Figure contains an axes object. The axes object contains an object of type line.

Extended Capabilities

在R2006a之前引入