Hello World in MATLAB
Your first MATLAB program - the classic Hello World example with Docker setup using GNU Octave
Every programming journey starts with Hello World. MATLAB makes this simple with its disp function.
The Code
Create a file named hello.m:
| |
One line — just like Python, MATLAB keeps Hello World simple.
Understanding the Code
disp()- A built-in function that displays text or variable values to the console'Hello, World!'- A character array (string) enclosed in single quotes- No semicolons needed for output - MATLAB uses semicolons to suppress output; omitting them prints the result
- No main function required - MATLAB scripts run top-to-bottom like a scripting language
Running with Docker (GNU Octave)
MATLAB is commercial software, so we use GNU Octave, a free and open-source alternative that is largely compatible with MATLAB syntax. The same .m files run in both environments.
| |
Docker Command Flags
--no-gui- Runs Octave in command-line mode (no graphical interface)--no-window-system- Prevents X11/display errors in headless environments like Docker
Running Locally
If you have MATLAB installed:
| |
Or with GNU Octave:
| |
Expected Output
Hello, World!
Alternatives to disp
MATLAB offers several ways to print output:
| |
disp()- Simple display, adds a newline automaticallyfprintf()- Formatted output (like C’sprintf), requires explicit\nfor newline- Semicolons - Adding
;at the end of a line suppresses output in the console
Key Concepts
- MATLAB is interpreted - Scripts run directly without a compilation step
- Everything is a matrix - Even the string
'Hello, World!'is a 1x13 character array - 1-based indexing - Arrays start at index 1, not 0 (matching mathematical convention)
.mfiles - MATLAB scripts and functions are saved with the.mextension- Interactive workspace - Variables persist in the workspace between commands
MATLAB vs. GNU Octave
For this Hello World example, the code is identical in both MATLAB and GNU Octave. Octave was specifically designed to be compatible with MATLAB’s core language, so most basic scripts work without modification.
Key compatibility notes:
- Core syntax - Virtually identical for scripts and functions
- Built-in functions - Most common functions (
disp,fprintf,plot, etc.) work the same way - Differences emerge - In advanced toolbox features, Simulink, and some OOP syntax
Running Today
All examples can be run using Docker:
docker pull gnuoctave/octave:9.4.0