MATLAB函数中的可选参数 [英] Optional args in MATLAB functions

查看:1784
本文介绍了MATLAB函数中的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆