MATLAB: Insert desired number of spaces in the string contains numerical value

formatting textMATLAB

Hi,
I need to print the below string which is in loop as
0 STR 1
where the first character is zero then 30 spaces then string STR and numerical 1 after five spaces
for this i wrote the statement as
txt = sprintf('0%30sSTR%5s%d',1);
But answer is not expected as above it gave the result as below
txt =
'0 STR'

Best Answer

The clearest way to achieve what you want is to put the spaces explicitly in your format string:
txt = sprintf('0 STR %d', istep)
or construct it explicitly:
txt = sprintf(['0', blanks(30), 'STR', blanks(5), '%d'], istep)
You could also use the format string that you've specified, by giving it spaces for the string formats:
txt = sprintf('0%30sSTR%5s%d', ' ', ' ', istep);
But in my opinion, it's less clear as to the intent than the other two options.