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 message
disp(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 the disp() function.

  • Line 3: It displays the value of the variable variable using the disp() 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 fprintf
fprintf('The value of x is %f\n', y); % Using fprintf

Explanation

  • Lines 1–2: It declares two variables x and y.

  • Line 3: It uses fprintf() to print the value of x. The %d specifier is used to format an integer, and %f is used to format a floating-point number. Since x is an integer, %d is used here. The \n is used for a newline character, which moves the cursor to the next line after printing.

  • Line 4: It uses fprintf() to print the value of y. Here, %f is used to format a floating-point number, as y is a floating-point number. Again, \n is 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.

Copyright ©2024 Educative, Inc. All rights reserved