Does MATLAB allow us to assign a default value for input arguments to a function like python?

I am working on a project and have many functions to create, and they need a lot of debugging, so instead of just clicking the start button, I have to go to the command window and give a function call.

Does MATLAB support assigning default values ​​for input arguments such as python?

In python

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

if you now call it without passing arguments, it gives no errors, but if you try the same in MATLAB, it will give an error.

+7
function arguments optional-parameters default-value matlab
source share
4 answers

To assign default values ​​is easier to manage if you use exist 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 the arguments, you do not need to update this part of the code, but when you use nargin , you need to start counting and updating the numbers.

+12
source share

If you are writing a complex function that requires checking inputs, default argument values, key-value pairs, transfer options as structures, etc., you can use inputParser . This solution is probably too large for simple functions, but you can remember your monstrous function that solves equations, displays results, and brings you coffee. This is a bit like what you can do with python argparse .

You configure inputParser as follows:

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

Inside a function, you usually call it with p.parse(varargin{:}) and look for your parameters in p.Results . Some quick demo 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. 
+7
source share

You can do it with nargin

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

but where did a and b come from? Are they dynamically assigned? Since this affects the fairness of this decision

After a few seconds of searching on Google, I found that, as often happens, Lauren Schure already solved this problem for us . In this article, she accurately describes my method above, why it is ugly and bad, and how to do better.

+5
source share

You can use nargin in your function code to determine when no arguments are passed, and assign default values ​​or do what you want in this case.

0
source share

All Articles