Search code examples
matlabfunctiontilde

Correct use of tilde operator for input arguments


Function:

My MATLAB function has one output and several input arguments, most of which are optional, i.e.:

output=MyFunction(arg1,arg2,opt1,opt2,...,optN)

What I want to do:

I'd like to give only arg1, arg2 and the last optional input argument optN to the function. I used the tilde operator as follows:

output=MyFunction(str1,str2,~,~,...,true)

Undesired result:

That gives the following error message:

Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

The error points to the comma after the first tilde, but I don't know what to make of it to be honest.

Problem identification:

  • I use MATLAB 2013b, which supports the tilde operator.

  • According to MATLAB's documentation the above function call should work:

    You can ignore any number of function inputs, in any position in the argument list. Separate consecutive tildes with a comma...

  • I guess there are a few workarounds, such as using '' or [] as inputs, but I'd really like to understand how to correctly use '~' because actually leaving inputs out allows me to use exist() when checking the input arguments of a function.

If you need any further info from me, please let me know.

Thank you very much!


Solution

  • The tilde is only for function declaration. Matlab's mlint recommends to replace unused arguments by ~. The result is a function declared like this function output = MyFunction(a, b, ~, c). This is a very bad practice.

    Since you have a function where the parameters are optional, you must call the function with empty arguments output=MyFunction(str1,str2,[],[],...,true).

    A better way to do it is to declare the function with the varargin argument and prepare your function for the different inputs:

    function output = MyFunction(varargin)
    
    if nargin == 1
        % Do something for 1 input
    elseif nargin == 2
        % Do something for 3 inputs
    elseif nargin == 3
        % Do something for 3 inputs
    else
        error('incorrect number of input arguments')
    end
    

    It is even possible to declare your function as follows:

    function output = MyFunction(arg1, arg2, varargin)
    

    The declaration above will tell Matlab that you are expecting at least two parameters.

    See the documentation of nargin here.

    ... and the documentation of varargin here