问题描述
在Matlab中是否可以使用默认参数?例如,在这里:
Is it possible to have default arguments in Matlab? For instance, here:
function wave(a, b, n, k, T, f, flag, fTrue=inline('0'))
我想让真正的解决方案成为wave函数的可选参数.如果有可能,任何人都可以演示执行此操作的正确方法吗?目前,我正在尝试上面发布的内容,并且得到了:
I would like to have the true solution be an optional argument to the wave function. If it is possible, can anyone demonstrate 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.
通常的方法是使用"varargs"并对照参数数量进行检查.像这样:
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.
您可能会看到varargin
,nargchk
等.它们对于这类事情很有用. 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中为函数参数设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!