MATLAB 函数中的可选参数 [英] Optional args in MATLAB functions
问题描述
如何使用可选参数在 MATLAB 中声明函数?
How can I declare function in MATLAB with optional arguments?
例如:function [a] = train(x, y, opt)
,其中 opt 必须是可选参数.
For example: function [a] = train(x, y, opt)
, where opt must be an optional argument.
推荐答案
关于如何执行此操作,有几个不同的选项.最基本的就是使用varargin
,然后使用nargin
、size
等来判断可选参数是否已经传递给函数.
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
一个看起来更优雅的解决方案是使用 inputParser
类来定义函数所需的所有参数,包括必需的和可选的.inputParser
还允许您对所有参数执行类型检查.
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.
这篇关于MATLAB 函数中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!