How to choose pass value to one parameter to a MATLAB function with multiple inputs?

536 views Asked by At

function [c,tc]=v_melcepst(s,fs,w,nc,p,n,inc,fl,fh)

This function has multiple input parameters, but I only want to specify the value for the nc parameter.

In Python, I can easily just do something like v_melcepst(nc=13), but I cannot find the equivalent for MATLAB.

Is this not possible in MATLAB? Do I have to pass default values?

2

There are 2 answers

0
Cris Luengo On BEST ANSWER

This is indeed not possible in MATLAB. The arguments are sequential, identified by their location in the argument list.

If you wrote the v_melcepst function yourself, you can rewrite it to accept "name/value pairs", the standard way in MATLAB to do named arguments. In this system, groups of two arguments together work as a single named argument. You would call the function as

 [c,tc] = v_melcepst('nc',nc);

You can implement this using the old inputParser class (introduced in R2007a), or with the new function arguments block (new in R2019b).

0
Adriaan On

Check the documentation on varargin and nargin.

Basically, do something like

function out = my_func(a,varargin)

if nargin == 1
    b = 2; % Your default value
elseif nargin == 2
    b = varargin{1};
end

Note that the above does mean you have to have a fixed order of input arguments. Any arguments explicitly named in the function declaration, a in this case, always have to be present, and anything within the varargin has to be in the set order, e.g. you can add a c = varargin{2}, then you cannot set c without setting b.

If you want to be able to give Python-like input argument, i.e. regardless of the order, you need name-value pairs. This is done via inputParser, as suggested in Cris Luengo's answer