森之张卫东 发表于 2015-10-11 16:55

varargin和varargout函数的妙用

下面是一个简单函数例子,这个函数拥有不同的参数数目。函数plotline任意数目的1×2行向量,每一个向量包含一个点(x,y)。函数把这些点连成线。注意这个函数也接受直线类型字符串,并把这些字符串转递给plot的函数。<blockquote><font size="4">function plotline(varargin)</font>我们用下面的参数调用这个函数,产生的图象如图7.5所示。用相同的数目的参数调用函数,看它产生的结果为什么?也有专门的输出参数,vargout,它支持不同数目的输出参数。这个参数显示在输出参数列表的最后一项。它返回一个单无阵列,所示单个输出实参支持任意数目的实参。每一个实参都是这个单无阵列的元素,存储在varargout。
如果它被应用,varargout必须是输出参数列表中最后一项,在其它输入参数之后。存储在varargout中的变量数由函数nargout确定,这个函数用指定于任何一个已知函数的输出实参。例如,我们要编写一函数,它返回任意数目的随机数。我们的函数可以用函数nargout指定输出函数的数目,并把这些数目存储在单元阵列varargout中。
图7.5 函数plotline产生的图象function = test2(mult)%   nvals is the number ofrandom values returned%   varargout contains therandom values returnednvals = nargout - 1;for ii = 1:nargout-1    varargout{ii} =randn *mult;end当这个函数被执行时,产生的结果如下>> test2(4)ans =    -1>> = test2(4)a =     3b =   -1.7303c =   -6.6623d =    0.5013好的编程习惯应用单元阵列varargin和varargout创建函数,这个函数支持不同数目的输入或输出参数。

森之张卫东 发表于 2015-10-11 17:20

function plotline(varargin)
%PLOTLINE Plot points specified by pairs.
% Function PLOTLINE accepts an arbitrary number of
% points and plots a line connecting them.
% In addition, it can accept a line specification
% string, and pass that string on to function plot.
% Define variables:
% ii                                        --Index variable
% jj                                        --Index variable
% linespec                  --String defining plot characteristics
% msg                     --Error message
% varargin                  --Cell array containing input arguments
% x                        --x values to plot
% y                        --y values to plot
% Record of revisions:
% Date       Programmer    Description of change
% ====      =========    =====================
% 10/20/98 S. J. Chapman     Original code
% Check for a legal number of input arguments.
% We need at least 2 points to plot a line...
msg = nargchk(2,Inf,nargin);
error(msg);
% Initialize values
jj = 0;
linespec = '';
% Get the x and y values, making sure to save the line
% specification string, if one exists.
for ii = 1:nargin
    % Is this argument an pair or the line
    % specification?
    if ischar(varargin{ii})
        % Save line specification
        linespec = varargin{ii};
    else
        % This is an pair. Recover the values.
        jj = jj + 1;
        x(jj) = varargin{ii}(1);
        y(jj) = varargin{ii}(2);
    end
end
% Plot function.
if isempty(linespec)
    plot(x,y);
else
    plot(x,y,linespec);
end

页: [1]
查看完整版本: varargin和varargout函数的妙用