By coincidence I discovered, that disp(fprintf())
prints the string of fprintf plus the number of characters that it has. I know, that the disp()
is reduntant, but just out of pure curiosity I want to know, why it prints the number of characters, since this might be actually helpful one day.
For example
disp(fprintf('Hi %i all of you',2))
results in
Hi 2 all of you 15
The reason for the specific behaviour mentioned in the question is the call to FILEprintf fprintf
with a storage variable:
nbytes = fprintf(___)
returns the number of bytes thatfprintf
writes, using any of the input arguments in the preceding syntaxes.
So what happens is that disp(fprintf(...))
first prints the text as per fprintf
without a storage variable, but disp
sees only the storage variable of fprintf
, which is the number of bytes of your string, hence the output.
As an addition, if you want to display strings, you need STRINGprintf: sprintf
:
disp(sprintf('Hi %i all of you',2))
Hi 2 all of you
What the docs show me is that sprintf
is exclusively used for string formatting, which you can use for adding text to a graph, setting up sequential file names etc, whilst fprintf
writes to a text file.
str = sprintf(formatSpec,A1,...,An)
formats the data in arraysA1
,...,An
according toformatSpec
in column order, and returns the results to stringstr
.
fprintf(fileID,formatSpec,A1,...,An)
applies theformatSpec
to all elements of arraysA1
,...An
in column order, and writes the data to a text file.fprintf
uses the encoding scheme specified in the call tofopen
.
fprintf(formatSpec,A1,...,An)
formats data and displays the results on the screen.
For displaying text on screen therefore disp(sprintf())
or fprintf
are equal, but if you want to store the results in a string you have to use sprintf
and if you want to write it to a text file you have to use fprintf
.
In the doc on fprintf
, you see that the output from fprintf
is the number of bytes printed. So here, the fprintf
is printing Hi 2 all of you
and the disp
is printing the 15 returned by fprintf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With