I create a function
function y = getValue(modelName, param, option)
open_system(modelName);
runModel(option);
y = getActiveFun(param);
end
I would like when calling this function to have the choice to pass or not argument option
from some other files I call the function with all arguments and sometimes I would like to call it without passing option
argument ?
I would like to call : getValue(modelName, param)
from other files
How could I do that ?
The standard way to handle optional arguments in a Matlab function is to put them at the end of the call list and only include them if you want to change them.
As a general rule, the way MATLAB handles missing inputs is to substitute the empty array [] for them in the function call. So to omit 'b': out = fcn(a,[],c); although 'b' would have to have a default value assigned in the function once it is detectred as missing.
varargin is an input variable in a function definition statement that enables the function to accept any number of input arguments. Specify varargin by using lowercase characters.
arg(Z) is the function returns argument of the complex number Z.
The simplest way to do this is to use the nargin
variable:
function y = getValue(modelName,param,option)
open_system(modelName);
if (nargin < 3)
# No option passed, do something like
runModel('defaultOption')
else
# Option passed
runModel(option);
end
y = getActiveFun(param);
end
nargin
is just the number of input arguments that were actually submitted. Thus, nargin == 3
indicates that the option parameter has been set, nargin < 3
that it has not been set.
Thus, you could now always call your function like
result = getValue('myModel', myParameter)
or with all parameters
result = getValue('myModel', myParameter, someOption)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With