Optional args in MATLAB functions

前端 未结 3 1103
醉酒成梦
醉酒成梦 2020-12-04 19:08

How can I declare function in MATLAB with optional arguments?

For example: function [a] = train(x, y, opt), where opt must be an optional argument.

3条回答
  •  离开以前
    2020-12-04 19:39

    There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

    % Function that takes two arguments, X & Y, followed by a variable 
    % number of additional arguments
    function varlist(X,Y,varargin)
       fprintf('Total number of inputs = %d\n',nargin);
    
       nVarargs = length(varargin);
       fprintf('Inputs in varargin(%d):\n',nVarargs)
       for k = 1:nVarargs
          fprintf('   %d\n', varargin{k})
       end
    

    A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

提交回复
热议问题