Search code examples
matlabfunctionargumentsdefault-valueoptional-parameters

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


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.


Solution

  • 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.