7

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.

Amro
  • 123,847
  • 25
  • 243
  • 454
hj-007
  • 332
  • 3
  • 6
  • 16
  • similar questions: [Default Arguments in Matlab](http://stackoverflow.com/q/795823), [How to deal with name/value pairs of function arguments in MATLAB](http://stackoverflow.com/q/2775263), and many other questions linked to those... – Amro Sep 22 '13 at 17:52

5 Answers5

13

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • 1
    Which still doesn't eliminate the need to change all calls to the function, if you change the order of arguments... – sebastian Sep 20 '13 at 19:05
  • 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? – liyuan Mar 07 '18 at 18:33
  • @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. – Mohsen Nosratinia Mar 08 '18 at 19:00
  • @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 – liyuan Mar 08 '18 at 23:12
7

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.
Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62
  • 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. – Adrian Sep 20 '13 at 16:22
  • There you go, I added an example. – Bas Swinckels Sep 20 '13 at 17:01
  • +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`. – Sam Roberts Sep 20 '13 at 22:32
  • That helps, I use the inputParser now even for the simplest of functions. Thanks – Adrian Sep 20 '13 at 23:26
5

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.

Dan
  • 45,079
  • 17
  • 88
  • 157
  • didn't understand your comment. – hj-007 Sep 20 '13 at 13:47
  • @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. – Dan Sep 20 '13 at 13:56
0

You can use nargin in your function code to detect when no arguments are passed, and assign default values or do whatever you want in that case.

am304
  • 13,758
  • 2
  • 22
  • 40
0

MathWorks has a new solution for this in R2019b, namely, the arguments block. There are a few rules for the arguments block, naturally, so I would encourage you to learn more by viewing the Function Argument Validation help page. Here is a quick example:

function ret = someFunction( x, y )
%SOMEFUNCTION Calculates some stuff.
    arguments
        x (1, :) double {mustBePositive}
        y (2, 3) logical = true(2, 3)
    end

% ...stuff is done, ret is defined, etc.
end

Wrapped into this is narginchk, inputParser, validateattributes, varargin, etc. It can be very convenient. Regarding default values, they are very simply defined as those arguments that equal something. In the example above, x isn't given an assignment, whereas y = true(2, 3) if no value is given when the function is called. If you wanted x to also have a default value, you could change it to, say, x (1, :) double {mustBePositive} = 0.5 * ones(1, 4).

There is a more in-depth answer at How to deal with name/value pairs of function arguments in MATLAB that hopefully can spare you some headache in getting acquainted with the new functionality.

benJephunneh
  • 658
  • 10
  • 14