How do I set default values for functions parameters in Matlab?
I've used the inputParser
object to deal with setting default options. MATLAB won't accept the Python-like format you specified in the question, but you should be able to call the function like this:
wave(a, b, n, k, T, f, flag, 'fTrue', inline('0'))
After you define the wave
function like this:
function wave(a, b, n, k, T, f, flag, varargin)
i_p = inputParser;
i_p.FunctionName = 'WAVE';
i_p.addRequired('a', @isnumeric);
i_p.addRequired('b', @isnumeric);
i_p.addRequired('n', @isnumeric);
i_p.addRequired('k', @isnumeric);
i_p.addRequired('T', @isnumeric);
i_p.addRequired('f', @isnumeric);
i_p.addRequired('flag', @isnumeric);
i_p.addOptional('ftrue', inline('0'), 1);
i_p.parse(a, b, n, k, T, f, flag, varargin{:});
Now the values passed into the function are available through i_p.Results
. Also, I wasn't sure how to validate that the parameter passed in for ftrue
was actually an inline
function, so I left the validator blank.
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
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.
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.