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

10,248

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
10,248
hj-007
Author by

hj-007

Updated on June 04, 2022

Comments

  • hj-007
    hj-007 almost 2 years

    I am working on a project and have many functions to create and they do need lots of debugging so instead of just hitting the run button i have to go to command window and give a function call.

    does MATLAB support assignment of default values to input arguments like python does?

    In python

    def some_fcn(arg1 = a, arg2 = b)
    % THE CODE
    

    if you now call it without passing the arguments it doesn't give errors but if you try the same in MATLAB it gives an error.

  • hj-007
    hj-007 over 10 years
    didn't understand your comment.
  • Dan
    Dan over 10 years
    @hj-007 which comment? I'm saying when do the default values get chosen? Anyway, it's irrelevant, there are better methods in the link I posted and even more in the comments on that link.
  • Felix Ribeiro
    Felix Ribeiro over 10 years
    I thought an example would be useful to illustrate the inputParser solution. The line p.addParamValue('highlight',true,@islogical); will make highlight a valid input key to the function;check that the input is logical and if not defined in the input highlight will default to true. Sorry about the formatting but editting the answer with an example was rejected.
  • Bas Swinckels
    Bas Swinckels over 10 years
    There you go, I added an example.
  • sebastian
    sebastian over 10 years
    Which still doesn't eliminate the need to change all calls to the function, if you change the order of arguments...
  • Sam Roberts
    Sam Roberts over 10 years
    +1 As long as you have a fairly recent version of MATLAB to include inputParser, this is much the most robust way of handling complex input argument syntaxes, including default arguments. Only if you have an old version should you need to fall back on syntaxes from other answers that use nargin or exists.
  • Felix Ribeiro
    Felix Ribeiro over 10 years
    That helps, I use the inputParser now even for the simplest of functions. Thanks
  • liyuan
    liyuan about 6 years
    am I missing something? This works only if you do this for variables at the end? You can't do this for arg2 only? Or maybe you are just demonstrating the concept?
  • Mohsen Nosratinia
    Mohsen Nosratinia about 6 years
    @liyuan, why can't you do this for arg2 only? It checks whether a variable named arg2 exists in the workspace of the function. If it does not exist, the variable with default value is created.
  • liyuan
    liyuan about 6 years
    @MohsenNosratinia because if you do f(arg1,arg3) you don't get the desired behavior of passing arg1 and arg3 and having arg2 assigned to default value