Reputation: 47
Is there a way to pass the inputted arguments in a function, varargin
, into an sprintf
command?
The problem is that sprint doesn't like cell inputs. I've tried using varargin{:}
and the series of mat2str(cell2mat( )
Ideally I want to have this in a loop
for k = varargin
filename = sprintf('%s.mat',i)
more code......
end
Thanks!
Upvotes: 1
Views: 775
Reputation: 4098
To help people landing here by googling for the title:
You can pass varargin
to sprintf
this way:
sprintf(format, varargin{:})
Matlab will convert cell array to comma-separated values, like
sprintf(format, varargin{1}, varargin{2}, ...)
Upvotes: 2
Reputation: 7817
You're nearly there, to be honest. Try this:
for k = 1:length(varargin)
filename = sprintf('%s.mat', varargin{k})
more code......
end
This assumes that all inputs are strings.
Another related and quite useful function is inputname
which you can use if you want to return the names of the variables passed in as arguments.
for k = 1:length(varargin)
filename = sprintf('%s.mat', inputname(k))
more code......
end
One thing to watch out for: inputname
returns an empty string if an input is unnamed.
Upvotes: 0