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 ofXin the command window.Xcan be a string, number, array, or any variable.dispdoes 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
fprintffor formatted output). - Passing multiple arguments to
disp(it accepts only one argument). - Expecting
dispto 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
| Usage | Description |
|---|---|
| disp(X) | Displays the value of X without variable name |
| X can be string, number, array | Any data type can be displayed |
| Only one argument allowed | Multiple arguments cause errors |
| No output returned | disp 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.