Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Pass varargin to a function accepting variable number of arguments

Tags:

matlab

Want to write a shorthand for fprintf(..).

varargin is a cell array. So how can I pass it to fprintf(..)? The latter only accepts a variable number of arrays.

The following doesn't work:

function fp(str, varargin)
    fprintf(str, varargin);
end

Giving

Error using fprintf
Function is not defined for 'cell' inputs.

or

Error: Unexpected MATLAB expression.
like image 557
Evgeni Sergeev Avatar asked Sep 24 '12 04:09

Evgeni Sergeev


People also ask

How do you find the number of input arguments in MATLAB?

Create a function called test_function that accepts any number of input arguments. Within the function, call iptchecknargin to check that the number of arguments passed to the function is within the range [1, 3]. Save the function with the file name test_function. m .

How many arguments can a function have MATLAB?

Functions can include only one repeating input arguments block.

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. After any explicitly declared inputs, include varargin as the last input argument .


1 Answers

The solution is:

function fp(str, varargin)
    fprintf(str, varargin{:});
end

The cell array is expanded into a comma-separated list using the {:} syntax.

A shortcut using an anonymous function is

fp = @(str, varargin) fprintf(str, varargin{:});
like image 194
Evgeni Sergeev Avatar answered Sep 22 '22 12:09

Evgeni Sergeev