如何在 MATLAB 中设置函数参数的默认值? [英] How do I set default values for functions parameters in MATLAB?

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

问题描述

MATLAB 中是否可以使用默认参数?

Is it possible to have default arguments in MATLAB?

例如,这里:

function wave(a, b, n, k, T, f, flag, fTrue=inline('0'))

我希望真正的解决方案是波函数的可选参数.如果可能,这样做的正确方法是什么?

I would like to have the true solution be an optional argument to the wave function. If it is possible, what is the proper way to do this?

目前,我正在尝试上面发布的内容并得到:

Currently, I am trying what I posted above and I get:

??? Error: File: wave.m Line: 1 Column: 37
The expression to the left of the equals sign is not a valid target for an assignment.

推荐答案

没有像您尝试过的那样直接的方法.

There isn't a direct way to do this like you've attempted.

通常的方法是使用可变参数";并检查参数的数量.比如:

The usual approach is to use "varargs" and check against the number of arguments. Something like:

function f(arg1, arg2, arg3)

  if nargin < 3
    arg3 =   'some default'
  end

end

您可以使用 isempty 等做一些更有趣的事情,您可能想查看 MATLAB Central 中的一些捆绑这些东西的软件包.

There are a few fancier things you can do with isempty, etc., and you might want to look at MATLAB central for some packages that bundle these sorts of things.

您可能会看看 vararginnargchk 等.它们是这类事情的有用函数.varargs 允许您保留可变数量的最终参数,但这并不能解决部分/全部参数的默认值问题.

You might have a look at varargin, nargchk, etc. They're useful functions for this sort of thing. varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.

这篇关于如何在 MATLAB 中设置函数参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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