Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disp(fprintf()) prints the fprintf and the number of characters. Why?

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

like image 870
Max Avatar asked Dec 01 '22 13:12

Max


2 Answers

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 that fprintf 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 arrays A1,...,An according to formatSpec in column order, and returns the results to string str.

fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen.

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.

like image 124
Adriaan Avatar answered Dec 06 '22 20:12

Adriaan


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.

like image 37
houtanb Avatar answered Dec 06 '22 21:12

houtanb