Evgeni Sergeev
Evgeni Sergeev

Reputation: 23593

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

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.

Upvotes: 14

Views: 10166

Answers (1)

Evgeni Sergeev
Evgeni Sergeev

Reputation: 23593

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{:});

Upvotes: 23

Related Questions