How do I set default values for functions parameters in MATLAB?
Solution 1
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.
Solution 2
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.
Solution 3
Another slightly less hacky way is
function output = fun(input)
if ~exist('input','var'), input='BlahBlahBlah'; end
...
end
Solution 4
Yes, it might be really nice to have the capability to do as you have written. But it is not possible in MATLAB. Many of my utilities that allow defaults for the arguments tend to be written with explicit checks in the beginning like this:
if (nargin<3) or isempty(myParameterName)
MyParameterName = defaultValue;
elseif (.... tests for non-validity of the value actually provided ...)
error('The sky is falling!')
end
Ok, so I would generally apply a better, more descriptive error message. See that the check for an empty variable allows the user to pass in an empty pair of brackets, []
, as a placeholder for a variable that will take on its default value. The author must still supply the code to replace that empty argument with its default value though.
My utilities that are more sophisticated, with many parameters, all of which have default arguments, will often use a property/value pair interface for default arguments. This basic paradigm is seen in the handle graphics tools in MATLAB, as well as in optimset, odeset, etc.
As a means to work with these property/value pairs, you will need to learn about varargin, as a way of inputting a fully variable number of arguments to a function. I wrote (and posted) a utility to work with such property/value pairs, parse_pv_pairs.m. It helps you to convert property/value pairs into a MATLAB structure. It also enables you to supply default values for each parameter. Converting an unwieldy list of parameters into a structure is a very nice way to pass them around in MATLAB.
Solution 5
This is my simple way to set default values to a function, using "try":
function z = myfun (a, varargin)
%% Default values
b = 1;
c = 1;
d = 1;
e = 1;
try
b = varargin{1};
c = varargin{2};
d = varargin{3};
e = varargin{4};
end
%% Calculation
z = a * b * c * d * e;
end
![Robert LaFondue](https://lh6.googleusercontent.com/-E_KYhCqdz7E/AAAAAAAAAAI/AAAAAAAAAFM/koXjKu-aTEU/photo.jpg?sz=256)
Robert LaFondue
Updated on May 11, 2022Comments
-
Robert LaFondue about 2 years
Is it possible to have default arguments in MATLAB?
For instance, here:
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.
-
gnovice about 15 yearsThere were a couple of errors in the code that I corrected. First, "optargin" needs to be defined. Second, "varargin" is a cell array that collects all subsequent inputs, so you have to use cell array indexing to remove values from it.
-
kyle about 15 yearsI need to get my vision checked; I swear I saw none of that in the manual yesterday :(
-
gnovice about 15 years@kyle: Not to worry, we all make mistakes. That's why I like SO's wiki-ish style: if I make some silly typo, there's usually someone else around who can catch it and fix it quickly for me. =)
-
JnBrymn over 13 yearsAs best I can tell, this, is the preferred method. It's clean, self-documenting (more so an a bunch of
if nargin
statemens), easy to maintain, compact, and flexible. -
equaeghe over 7 yearsThe link to your follow-up blog post is broken; can you fix it?
-
Dave Tillman over 6 yearsThis option doesn't work if you are going to use MATLAB Coder to generate C code, as Coder does not support the "exist" function.
-
Cris Luengo about 6 yearsWhy not follow the MATLAB standard of name-value pairs?
wave(a,b,'flag',42,'fTrue',1)
-
CheshireCat about 6 yearsThis is certainly an option as well, especially when one has only few parameters. Calling wave() with a big number of name-value pairs, however, might reduce the readability of the code. I therefore often prefer to group certain inputs into structs.
-
MacroController over 3 yearsThis answer needs more visibility. I remembered the blog post from Loren, and was looking for it, and opened this stackoverflow question in the hope I would find it easily that way.
-
Peter Mortensen over 3 yearsCan you elaborate?
-
Andrew Janke over 3 yearsPlease don't edit this answer to put "MATLAB" in all caps. I realize that's the official styling for it, but it seems like shouting to me, so I don't use it in my own writing.
-
Mr Fooz over 3 yearsI've pasted in the documentation. It shows a sketch of how to use it to set default values.
-
alisianoi over 2 years> The link to your follow-up blog post is broken; can you fix it? <br/> web.archive.org/web/20160711181129/http://all3fox.github.io/…
-
Dongdong Kong about 2 yearswhy no body vote for this answer?