MATLAB函数中的可选参数 [英] Optional args in MATLAB functions
问题描述
例如: function [a] = train(x,y,opt )
,其中opt必须是可选参数。
去做这个。最基本的是使用 varargin
,然后使用 nargin
, size
等来确定是否已传递可选参数
%带有两个参数的函数,X& Y,其后是变量
%的附加参数数量
函数varlist(X,Y,varargin)
fprintf('输入总数=%d \ n',nargin);
nVarargs =长度(varargin);
fprintf('varargin中的输入(%d):\ n',nVarargs)
for k = 1:nVarargs
fprintf('%d \'',varargin {k} )
end
稍微优雅的解决方案是使用 inputParser
类定义您的函数所需的所有参数都是必需的和可选的。 inputParser
还允许您对所有参数执行类型检查。
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.
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.
这篇关于MATLAB函数中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!