数学建模社区-数学中国
标题: varargin和varargout函数的妙用 [打印本页]
作者: 森之张卫东 时间: 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 [nvals, varargout] = test2(mult)
% nvals is the number ofrandom values returned
% varargout contains therandom values returned
nvals = nargout - 1;
for ii = 1:nargout-1
varargout{ii} =randn *mult;
end
当这个函数被执行时,产生的结果如下
>> test2(4)
ans =
-1
>> [a b c d] = test2(4)
a =
3
b =
-1.7303
c =
-6.6623
d =
0.5013
好的编程习惯
应用单元阵列varargin和varargout创建函数,这个函数支持不同数目的输入或输出参数。
-
图7.5 函数plotline产生的图象.JPG
(32.43 KB, 下载次数: 135)
作者: 森之张卫东 时间: 2015-10-11 17:20
- function plotline(varargin)
- %PLOTLINE Plot points specified by [x,y] pairs.
- % Function PLOTLINE accepts an arbitrary number of
- % [x,y] 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 [x,y] pair or the line
- % specification?
- if ischar(varargin{ii})
- % Save line specification
- linespec = varargin{ii};
- else
- % This is an [x,y] 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
复制代码
| 欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) |
Powered by Discuz! X2.5 |