Proper use of the tilde operator for input arguments

Function:

The MATLAB function has one output and several input arguments, most of which are optional, that is:

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

What I want to do:

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

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

Undesirable result:

This gives the following error message:

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

The error indicates a comma after the first tilde, but I do not know what to do with it, to be honest.

Problem Identification:

  • I am using MATLAB 2013b, which supports the tilde operator.
  • According to the MATLAB documentation, the above function call should work:

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

  • I think there are some workarounds, such as using '' or [] as input, but I would really like to understand how to use '~' correctly, because in fact leaving the input, I can use the existing ( ) when checking the input arguments of a function.

If you need more information from me, please let me know.

Many thanks!

+7
function matlab tilde
source share
2 answers

Tilda is for function declaration only. Matlab mlint recommends replacing unused arguments with ~ . The result is a function declared as function output = MyFunction(a, b, ~, c) . This is a very bad practice.

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

The best way to do this is to declare a function with varargin argument and prepare your function for 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 

You can even declare your function as follows:

 function output = MyFunction(arg1, arg2, varargin) 

In the above description, Matlab will indicate that you expect at least two parameters.

See nargin documentation here .

... and the varargin documentation here

+8
source share

To have a variable number of inputs, use varargin . Use it with a nargin.

Example:

 function varlist2(X,Y,varargin) fprintf('Total number of inputs = %d\n',nargin); nVarargs = length(varargin); fprintf('Inputs in varargin(%d):\n',nVarargs) for k = 1:nVarargs fprintf(' %d\n', varargin{k}) end 
+4
source share

All Articles