Confusing sprintf() behavior
7 次查看(过去 30 天)
显示 更早的评论
>> 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 个评论
采纳的回答
Stephen23
2024-3-4
编辑:Stephen23
2024-3-4
"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).
更多回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!