MATLAB: How to call a function with an incomplete argument list and set default values for the arguments that were not supplied

argumentsdefaultdifferentenoughinputMATLABnarginnotnumberparameterssupplyvararginvariable

I have defined a function that takes in 4 input parameters, and I want to be able to call it with either 3 or 4 arguments. If the 4th argument is not supplied, I want it to default to be an empty list [] .
However, right now when I call my function with 3 parameters, I get the error "Not enough input arguments".
I would like to call my function 'solver' in the following ways:
>> solver(h_odefun, tspan, y0)
>> solver(h_odefun, tspan, y0, opts)
'solver' is defined as the following:
function [t, y] = solver(h_odefun, tspan, y0, options)
[t,y] = ode45(h_odefun, tspan, y0, options);
end
I would like 'options' to default to [] if the argument is not supplied.

Best Answer

You are getting the error 'Not enough input arguments' because your function is expecting 4 input arguments, but the last one has not been defined. The function cannot run the line " [t,y] = ode45(h_odefun, tspan, y0, options); " because the variable 'options' is not defined.
There are multiple ways you can resolve this error.
1. Use 'nargin' to determine when the function has been called with an incomplete argument list, and define the missing arguments before the function attempts to use them. For more information about 'nargin', see this documentation page: https://www.mathworks.com/help/matlab/ref/nargin.html.
Example:
function [t, y] = solver(h_odefun, tspan, y0, options)
if nargin < 4
options = []
end
[t,y] = ode45(h_odefun, tspan, y0, options);
end
2. Use 'varargin' to enable the function to accept any number of arguments. See this documentation page for more information: https://www.mathworks.com/help/matlab/ref/varargin.html.
Example:
function [t, y] = solver(varargin)
h_odefun = varargin{1};
tspan = varargin{2};
y0 = varargin{3};
if nargin < 4
options = [];
else
options = varargin{4};
end
[t,y] = ode45(h_odefun, tspan, y0, options);
end
For additional examples of how to write a function that takes in a variable number of input arguments, see the following posts: