0
0
MatlabHow-ToBeginner ยท 3 min read

How to Use disp in MATLAB: Syntax and Examples

In MATLAB, use the disp function to display text or variable values in the command window without printing the variable name. Simply pass the text or variable as an argument to disp, like disp('Hello') or disp(x).
๐Ÿ“

Syntax

The basic syntax of disp is simple:

  • disp(X): Displays the value of X in the command window.
  • X can be a string, number, array, or any variable.
  • disp does not display the variable name, only its value.
matlab
disp(X)
๐Ÿ’ป

Example

This example shows how to display a string and a numeric variable using disp.

matlab
message = 'Hello, MATLAB!';
number = 42;
disp(message)
disp(number)
Output
Hello, MATLAB! 42
โš ๏ธ

Common Pitfalls

Common mistakes when using disp include:

  • Trying to display variable names along with values (use fprintf for formatted output).
  • Passing multiple arguments to disp (it accepts only one argument).
  • Expecting disp to return a value (it only prints output).
matlab
x = 10;
% Wrong: disp('x = ', x)  % This causes an error

% Right way:
disp(['x = ', num2str(x)])
Output
x = 10
๐Ÿ“Š

Quick Reference

UsageDescription
disp(X)Displays the value of X without variable name
X can be string, number, arrayAny data type can be displayed
Only one argument allowedMultiple arguments cause errors
No output returneddisp only prints to command window
โœ…

Key Takeaways

Use disp(X) to print the value of X without showing the variable name.
disp accepts only one input argument, which can be text or any variable.
For formatted output with variable names, use fprintf instead of disp.
disp prints output to the command window and does not return any value.