MATLAB函数可选参数设置




在编写函数时会遇到这种情况,多个参数可能不同时用,就会想到设置默认值,此时就要用到nargin和nargout。
nargin, nargout


Number of function arguments 
Syntax 


nargin
nargin(fun)
nargout
nargout(fun)

Description


In the body of a function M-file, nargin and nargout indicate how many input or output arguments, respectively, a user has supplied. Outside the body of a function M-file, nargin and nargout indicate the number of input or output arguments, respectively, for a given function. The number of arguments is negative if the function has a variable number of arguments.

nargin returns the number of input arguments specified for a function.

nargin(fun) returns the number of declared inputs for the function fun. If the function has a variable number of input arguments, nargin returns a negative value. fun may be the name of a function, or the name of Function Handles that map to specific functions.

nargout returns the number of output arguments specified for a function.

nargout(fun) returns the number of declared outputs for the function fun. fun may be the name of a function, or the name of Function Handles that map to specific functions.
Examples


This example shows portions of the code for a function called myplot, which accepts an optional number of input and output arguments:
function [x0, y0] = myplot(x, y, npts, angle, subdiv)
% MYPLOT  Plot a function.
% MYPLOT(x, y, npts, angle, subdiv)
%     The first two input arguments are
%     required; the other three have default values.
 ...
if nargin < 5, subdiv = 20; end
if nargin < 4, angle = 10; end
if nargin < 3, npts = 25; end
 ...
if nargout == 0
     plot(x, y)
else
     x0 = x;
     y0 = y;
end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值