txt = sprintf('%*.2f', 5, 123.45678)
txt =
'123.46'
Specify Numbered Identifiers in Width and Precision Fields
You also can specify field width and precision as values from a nonsequential argument
list, using an alternate syntax shown in the figure. Within the formatting operator, specify
the field width and precision with asterisks that follow numbered identifiers and $ signs.
Specify the values of the field width and precision with input arguments that follow the
format specifier.
For example, format and display three numbers. In each case, use a numbered identifier
to specify that the field width or precision come from input arguments that follow the
format specifier.
txt = sprintf('%1$*4$f %2$.*5$f %3$*6$.*7$f',...
123.45678, 16.42837, pi, 15, 3, 6, 4)
txt =
' 123.456780 16.428 3.1416'
The table describes the effect of each formatting operator in the example.
Formatting Operator Description
%1$*4$f 1$ specifies the first input argument,
123.45678, as the value
*4$ specifies the fourth input argument,
15 , as the field width
%2$.*5$f 2$ specifies the second input argument,
16.42837, as the value
.*5$ specifies the fifth input argument, 3 ,
as the precision
6 Characters and Strings