例题:选择性参数的应用 通过创建函数把直角坐标值(x,y)转化相应的极坐标值,我们向大家说选择性参数的应用。这个函数支持两个输入参数,x和y。但是,如果支持只有一个参数的情况,那么函数就假设y值为0,并使用它进行运算。函数在一般情况下输出量为模与相角(单位为度)。但只有一个输出参数只有一个时,它只返回模。函数如下所示。
function [mag, angle] = polar_value(x, y) % POLAR_VALUE Converts(x, y) to (r, theta) % Punction POLAR_VALUE converts an input(x,y) % va1ue into (r, theta), with theta in degrees. % It illustrates the use of optional arguments. % Define variables: % angle --Angle in degrees % msg --Error message % mag --Magnitude % x --Input x value % y --Input y value(optional) % Record Of revisions: % Date Programmer Description of change % ======== ============== ======================== % 12/16/98 S.J.Chapman Original code % Check for a legal number of input arquments msg = nargchk(1,2,nargin); error(msg); % If the y argument is missing, set it to 0. if nargin < 2 y = 0; end % Check for (0,0) input argument, and print out % a warning message. if x == 0 & y == 0 msg = 'Both x and y are zero: angle is meaningless!'; warning(msg); end % Now calculate the magnitude mag = sqrt(x .^2 + y .^2); % If the second output argument is present,calculate % angle in degrees if nargout == 2 angle = atan2(y,x) * 180/pi; end
我们通过在命令窗口反复调用这个函数来检测它。首先,我们用过多或过少的参数来调用这个函数。
>> [mag angle]=polar_value ??? Error using ==> polar_value Not enough input arguments. >> [mag angle]=polar_value(1,-1,1) ??? Error using ==> polar_value Too many input arguments.
在两种情况下均产生了相应的错误信息。我们将用一个参数或两个参数调用这个函数。
>> [mag angle]=polar_value(1) mag = 1 angle = 0 >> [mag angle]=polar_value(1,-1) mag = 1.4142 angle = -45
在这两种情况下均产生了正确的结果。我们调用这个函数使之输出有一个或两个参数。
>> mag = polar_value(1,-1) mag = 1.4142 >> [mag angle]=polar_value(1,-1) mag = 1.4142 angle = -45
这个函数提供了正确的结果。最后当x=0,y=0时,调用这个函数。
>> [mag angle] = polar_value(0,0) Warning: Both x and y are zero: angle is meaningless! > In polar_value at 27 mag = 0 angle = 0
在这种情况下,函数显示了警告信息,但执行继续。 注意一个MATLAB函数将会被声明有多个输出函数,超出了实际所需要的,这是一种错误。事实上,函数没有必要调用函数nargout来决定是否有一个输出参数存在。例如,考虑下面的函数。
function [z1, z2] = junk(x, y) z1 = x + y; z2 = x - y;
这个函数输出可以有一个或两个输出参数。
>> a = junk(2,1) a = 3 >> [a b] = junk(2,1) a = 3 b = 1
在一个函数中检查nargout的原因是为了防止无用的工作。如果我们找不到输出结果,为什么不在第一位置计算出来?程序员可以不必为无用的运算耐恼,也能加速程序的运算。
|