Confusing sprintf() behavior

10 views (last 30 days)
cr
cr on 4 Mar 2024
Commented: cr on 4 Mar 2024
>> sprintf('%.3f ',[.1 .2 .3])
ans =
'0.100 0.200 0.300 '
>> sprintf('%s, %.3f ',datestr(now),[.1 .2 .3])
ans =
'01-Mar-2024 11:37:57, 0.100 2.000000e-01, 0.300'
Why does a part of the output of sprintf get affected by an unleated %s specification. This doesn't happen if %.3f if repeated once for each of the 3 numbers. Is this a bug?

Accepted Answer

Stephen23
Stephen23 on 4 Mar 2024
Edited: Stephen23 on 4 Mar 2024
"Is this a bug?"
No.
SPRINTF and FPRINTF apply the entire format string to the data values, repeating the entire format string as required (not just part of the format string like you incorrectly assumed**). Basically your code is equivalent to doing this:
sprintf('%s, %.3f ',datestr(now),0.1) % applies the format string to 1st & 2nd values...
ans = '04-Mar-2024 09:29:21, 0.100 '
sprintf('%s, %.3f ',0.2,0.3) % then repeats the *entire* format string to 3rd & 4th values.
ans = '2.000000e-01, 0.300 '
which because 0.2 is not a valid text input then SPRINTF will revert to the default '%e' (which is also documented):
sprintf('%s, %.3f ',datestr(now),0.1)
ans = '04-Mar-2024 09:29:21, 0.100 '
sprintf('%e, %.3f ',0.2,0.3)
ans = '2.000000e-01, 0.300 '
** How would that even work? Consider this example:
sprintf('%.23f %.1g ',0.1,0.2,0.3)
With your proposed concept, how would SPRINTF know which part of the format string gets repeated for which input values? Where exactly in that syntax can I see that specified? What output would you expect to get?
Perhaps you expect the format string to be applied to the input arrays, so that the 1st part of the format string is applied to the 1st input array (regardless of how many values it has), the 2nd part of the format string is applied to the 2nd input array (regardless of how many values it has), etc. But that is incorrect. The SPRINTF documentation states very clearly that it applies the format string to the input values (not array-by-array as you might incorrectly expect).
  2 Comments
Stephen23
Stephen23 on 4 Mar 2024
Edited: Stephen23 on 4 Mar 2024
Whereas your first example is basically equivalent to this:
sprintf('%.3f ',0.1) % apply entire format string to 1st value
ans = '0.100 '
sprintf('%.3f ',0.2) % apply entire format string to 2nd value
ans = '0.200 '
sprintf('%.3f ',0.3) % apply entire format string to 3rd value
ans = '0.300 '
cr
cr on 4 Mar 2024
Thanks mate.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!