Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab function with argument not required

Tags:

matlab

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 ?

like image 967
lola Avatar asked Nov 22 '12 12:11

lola


People also ask

How do you make a function argument optional in MATLAB?

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.

How do you skip inputs in MATLAB?

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.

What does Varargin mean in MATLAB?

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.

What is Arg MATLAB?

arg(Z) is the function returns argument of the complex number Z.


1 Answers

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)
like image 139
Thilo Avatar answered Sep 22 '22 15:09

Thilo