disp() vs. fprintf() functions in MATLAB
In MATLAB, we use the fprintf() and disp() functions to display output, and they serve different purposes and have different formats.
The disp() function
It is primarily used for displaying the value of variables or simple messages in the command window. It is convenient for quickly displaying values or messages without much formatting. It automatically adds a newline character after displaying the content.
Example
We can simply print variables or messages using (). disp('Hello, world!'), which will print 'Hello, world!' on the screen.
variable = 10;disp('Hello, world!'); % Display a messagedisp(variable); % Display the value of a variable
Explanation
Line 1: It declares a variable named
variable.Line 2: It displays the message
"Hello, world!"using thedisp()function.Line 3: It displays the value of the variable
variableusing thedisp()function.
The fprintf() function
It is used to print text with formatting on a command window or a file. It allows us to control the output format, such as the amount of decimal places and string formatting. It is more adaptable than disp() for formatting output, particularly when dealing with numerical numbers or producing prepared text output. It does not add a newline character unless expressly requested.
Example
We can use a format specifier for different data types. %d is a format specifier for integers. We can use other format specifiers like %f for floating-point numbers, %s for strings, etc.
x = 10;y = 5.5;fprintf('The value of x is %d\n', x); % Using fprintffprintf('The value of x is %f\n', y); % Using fprintf
Explanation
Lines 1–2: It declares two variables
xandy.Line 3: It uses
fprintf()to print the value ofx. The%dspecifier is used to format an integer, and%fis used to format a floating-point number. Sincexis an integer,%dis used here. The\nis used for a newline character, which moves the cursor to the next line after printing.Line 4: It uses
fprintf()to print the value ofy. Here,%fis used to format a floating-point number, asyis a floating-point number. Again,\nis used to move the cursor to the next line after printing.
Conclusion
The disp() function is simpler and more convenient for quick display of messages or variable values, while the fprintf() function provides more control over formatting for displaying output, especially when dealing with numerical data or generating formatted text.
Free Resources