Does MATLAB lets you assign default value for input arguments for a function like python does?

For assigning default values, one might find it easier to manage if you use exist function instead of nargin.

function f(arg1, arg2, arg3)
if ~exist('arg2', 'var')
    arg2 = arg2Default;
end

The advantage is that if you change the order of arguments, you don't need to update this part of the code, but when you use nargin you have to start counting and updating numbers.


If you are writing a complex function that requires validation of inputs, default argument values, key-value pairs, passing options as structs etc., you could use the inputParser object. This solution is probably overkill for simple functions, but you might keep it in mind for your monster-function that solves equations, plots results and brings you coffee. It resembles a bit the things you can do with python's argparse module.

You configure an inputParser like so:

>> p = inputParser();
>> p.addRequired('x', @isfinite)       % validation function
>> p.addOptional('y', 123)             % default value
>> p.addParamValue('label', 'default') % default value

Inside a function, you would typically call it with p.parse(varargin{:}) and look for your parameters in p.Results. Some quick demonstration on the command line:

>> p.parse(44); disp(p.Results)
    label: 'default'
        x: 44
        y: 123
>> p.parse()
Not enough input arguments.
>> p.parse(Inf)
Argument 'x' failed validation isfinite.
>> p.parse(44, 55); disp(p.Results)
    label: 'default'
        x: 44
        y: 55
>> p.parse(13, 'label', 'hello'); disp(p.Results)
    label: 'hello'
        x: 13
        y: 123
>> p.parse(88, 13, 'option', 12)
Argument 'option' did not match any valid parameter of the parser.

You can kind of do this with nargin

function out = some_fcn(arg1, arg2)
    switch nargin
       case 0
             arg1 = a;
             arg2 = b;
    %//etc
end

but where are a and b coming from? Are they dynamically assigned? Because that effects the validity of this solution

After a few seconds of googling I found that as is often the case, Loren Shure has already solved this problem for us. In this article she outlines exactly my method above, why it is ugly and bad and how to do better.