I have written a Matlab R2020b function that optionally receives three inputs – but if the inputs are not received, they should be set to the defaults within the script.
function my_opt_func(opt1, opt2, opt3)
if (~exist(opt1, 'var'))
opt1 = setopt1();
end
if (~exist(opt2, 'var'))
opt2 = setopt2();
end
if (~exist(opt3, 'var'))
opt3 = setopt3();
end
disp(string(opt1) + string(opt2) + string(opt3))
function opt1 = setopt1()
opt1 = 1;
end
function opt2 = setopt2()
opt2 = 2;
end
function opt3 = setopt3()
opt3 = 3;
end
end
Here, the different setopt
functions are used to generate the appropriate default values.
Unfortunately, calling this function without parameters, as my_opt_func
or my_opt_func()
gives the error Not enough input arguments
. I tried using a variant of varargin
, but got the same error.
When I set the values without using the setopt
functions, I don’t get this error – but due to the complexity of my actual program, I really need to use functions to develop my defaults.
How do I fix this error so that the user can call the function with or without parameters – as either my_opt_func()
or my_opt_func(param1, param2, param3)
?