I have made some helper functions that run a simulation using a lot of functions inside them.
In order to make these helper functions more user friendly I want to give the user the choice of calling the functions with fewer arguments (the arguments that are not passed into the function are assigned a predefined value).
For example if I have a function
function [res, val, h, v, u] = compute(arg1, arg2, arg3, arg4)
if nargin < 4 || isempty(arg4) arg4 = 150; end
and the function runsim which is defined like this
function [res, val, h, v, u] = runsim(v, arg1, arg2, arg3, arg4)
the silly way to do it is
if nargin < 5 || isempty(arg4)
compute(arg1, arg2, arg3)
else
compute(arg1, arg2, arg3, arg4)
end
Another solution would be to change the arguments to vectors but I am not allowed to touch the functions behind the simulation. Is there a Matlab way to handle this situation or do I have to write the same code again and again with fewer arguments?
You can pack and unpack function arguments using cell arrays:
The same goes for output arguments:
Since varargin is also a cell array, you can just pop the field the function you want to execute is in, and then pass the rest of the fields as arguments to the function.