Difference between disp and fprintf

Y-MinG picture Y-MinG · Nov 1, 2018 · Viewed 16.3k times · Source

In Matlab, it seems to me that disp and fprintf commands both are very similar in that they both show to display what you tell it to. What is the difference between these 2 commands?

Answer

Banghua Zhao picture Banghua Zhao · Nov 1, 2018

For disp, it displays the value of variable.

For example

>> a = 1; disp(a)
     1

Another example.

>> disp('example')
example

Note, 'example' can be seen as a variable

Reference: https://www.mathworks.com/help/matlab/ref/disp.html


For fprintf, if you are talking about displaying to the screen, the format is

fprintf(formatSpec,A1,...,An) formats data and displays the results on the screen.

The difference to disp is that it doesn't display the value of variable unless you specify format string

For example, if you tend to display the value of a variable, you get an error

>> a = 1; fprintf(a)
Error using fprintf
No format string.

You need to specify the format string. For example, the format string is 'The value of a is %d\n'

a = 1; fprintf('The value of a is %d\n',a)
The value of a is 1

If you are talking about writing data to text file, the format is

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.

For example

fileID = fopen('exp.txt','w');
fprintf(fileID,'The number is %d\n',1);
fclose(fileID);

View the contents of the file with the type command.

>> type exp.txt

The number is 1

The fprintf can also return the number of bytes that fprintf writes. Refer to this answer

Reference: https://www.mathworks.com/help/matlab/ref/fprintf.html