Matlab's Strange Behavior

>> fprintf('%4d, %1.6f, %1.6f\n',1, 1.1, 1.2)
1, 1.100000, 1.200000
>> disp(fprintf('%4d, %1.6f, %1.6f\n',1, 1.1, 1.2))
1, 1.100000, 1.200000
25
Could anybody shed some light on this behavior? I don't know if I am doing anything wrong here, redundant of course. The function 'sprintf()' works as expected and does not print any other number not in the argument list.
It is not always '25', I have seen 23 and something else. I cannot remember or reproduce the third number, even after repeated attempts.
Thanks!

回答 (1 件)

Walter Roberson
Walter Roberson 2013 年 5 月 1 日

0 投票

fprintf() returns the number of bytes written. You would get the same result from
length(sprintf('%4d, %1.6f, %1.6f\n',1, 1.1, 1.2))
However, if you are writing to a file, fprintf() might end up translating into a different character set based upon the encoding set for the file; also, if the file is set as a text file ('wt') then on an MS Windows system the \n might get translated to 2 bytes.

3 件のコメント

Gurudatha Pai
Gurudatha Pai 2013 年 5 月 1 日
So, there were 25 bytes written to the console! Is that 25 ascii characters?
Is my understanding correct then? The string is written to the console by the fprintf function and the disp prints out the output of fprintf, i.e. number of bytes fprintf wrote?
Image Analyst
Image Analyst 2013 年 5 月 1 日
Correct. I don't even use disp. If I want the variable, I use fprintf() or simply just put the variable name all by itself on its own line. Why bother with disp()?
Walter Roberson
Walter Roberson 2013 年 5 月 1 日
disp() cancels the line printing out the name of the variable that would be given by putting the variable name all by itself. Putting the variable name all by itself may be required if the class of the variable is unknown or if it contains mixed data or if is a cell array... or structure... or object...

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

質問済み:

2013 年 5 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by