Confusing sprintf() behavior

7 次查看(过去 30 天)
cr
cr 2024-3-4
评论: cr 2024-3-4
>> 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?

采纳的回答

Stephen23
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...
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 个评论
Stephen23
Stephen23 2024-3-4
编辑:Stephen23 2024-3-4
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 '

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by