I am trying to define the following function in MATLAB:
file = @(var1,var2,var3,var4) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4)'];
However, I want the function to expand as I add more parameters; if I wanted to add the variable vark
, I want the function to be:
file = @(var1,var2,var3,var4,vark) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4) 'vark=' num2str(vark)'];
Is there a systematic way to do this?
Use fprintf
with varargin
for this:
f = @(varargin) fprintf('var%i= %i\n', [(1:numel(varargin));[varargin{:}]])
f(5,6,7,88)
var1= 5
var2= 6
var3= 7
var4= 88
The format I've used is: 'var%i= %i\n'
. This means it will first write var
then %i
says it should input an integer. Thereafter it should write =
followed by a new number: %i
and a newline \n
.
It will choose the integer in odd positions for var%i
and integers in the even positions for the actual number. Since the linear index in MATLAB goes column for column we place the vector [1 2 3 4 5 ...]
on top, and the content of the variable in the second row.
By the way: If you actually want it on the format you specified in the question, skip the \n
:
f = @(varargin) fprintf('var%i= %i', [(1:numel(varargin));[varargin{:}]])
f(6,12,3,15,5553)
var1= 6var2= 12var3= 3var4= 15var5= 5553
Also, you can change the second %i
to floats (%f
), doubles (%d
) etc.
If you want to use actual variable names var1, var2, var3, ...
in your input then I can only say one thing: Don't! It's a horrible idea. Use cells, structs, or anything else than numbered variable names.
Just to be crytsal clear: Don't use the output from this in MATLAB in combination with eval
! eval
is evil. The Mathworks actually warns you about this in the official documentation!