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.
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 .
Functions can include only one repeating input arguments block.
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 .
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{:});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With