From: Andy on
"Rajesh " <rv_acharya(a)rediffmail.com> wrote in message <i43cdm$52c$1(a)fred.mathworks.com>...
>
> > sprintf('%03d', 1);
> >
> > will achieve this (presuming ypu want to pad out to three decimal places);
>
> Thanks MM, what if i do not know how many zeros are to be padded with. i.e. I wouldnt know if its %03d beforehand. however it will be available to me as a variable. Can i use this variable in this way.
>
> e.g.
> sprintf('% var d',1);
> var can be defined just before this statement.

You can build up your format string for sprintf by concatenating strings with brackets:

var = 5; % var is a number representing total number of digits
sprintf(['%0' str2double(var) 'd'],1);
From: Walter Roberson on
Rajesh wrote:
>
>> sprintf('%03d', 1);
>> will achieve this (presuming ypu want to pad out to three decimal
>> places);
>
> Thanks MM, what if i do not know how many zeros are to be padded with.
> i.e. I wouldnt know if its %03d beforehand. however it will be available
> to me as a variable. Can i use this variable in this way.
>
> e.g. sprintf('% var d',1);
> var can be defined just before this statement.

Hint:

>> sprintf('%0*d',5,13)
ans =
00013