MATLAB: How to write sprintf with an argument for the number width

imagelabel;MATLABsaveassprintf

I'm writing a code to save figures one by one in a loop each with a filename Figure i, like so
for j=1:n+1
%plot code excluded%
folder='Vortex Pair';
name=sprintf('Figure %03d',j);
saveas(gca,[pwd fullfile('/',folder,name)],'png')
end
However I don't always know how many figures will be saved, so ideally I want the %03d part of my above code to have a number instead of 3 which is the number of digits in n+1. For n+1=1001|images, I would use |c=ceil(log10(1001))=4 then some code may read %0cd where c is predetermined as 4. An example with 1001 images, each saved figure name will be labeled 0001, 0002,… . The loop is not a problem, an example code which could be used to solve my issue would be
n=1001;
j=7;
name=sprintf('Figure %03d',j);

Best Answer

c = ceil(log10(n+1));
fmt = sprintf('Figure %%0%dd', c);
Then
name = sprintf(fmt, j);
Alternately:
c = ceil(log10(n+1));
and
name = sprintf('Figure %0*d', c, j)
The second of those is what you were asking about: the * in the width field for output formats tells it to take the next output item as being the width to use.