Confusing sprintf() behavior
10 views (last 30 days)
Show older comments
>> 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?
0 Comments
Accepted Answer
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...
sprintf('%s, %.3f ',0.2,0.3) % then repeats the *entire* format string to 3rd & 4th values.
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)
sprintf('%e, %.3f ',0.2,0.3)
** 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
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
sprintf('%.3f ',0.2) % apply entire format string to 2nd value
sprintf('%.3f ',0.3) % apply entire format string to 3rd value
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!