Coding · Programming languages
MATLAB tutorial for beginners
Short answer
MATLAB is a numerical computing language and environment from MathWorks in which every value is a matrix. You write A * B for a matrix product, A .* B for element-wise multiplication, index from 1, and replace many loops with vectorized expressions. It includes plotting and a large set of toolboxes for engineering and science. GNU Octave is a free, open-source alternative that runs most basic MATLAB code unchanged.
What MATLAB is and who uses it
MATLAB ("matrix laboratory") began as a tool by Cleve Moler for easy access to linear algebra libraries and became a commercial product of MathWorks. It combines a language, an interactive desktop, plotting, and toolboxes for signal processing, control systems, optimization, statistics, image processing and machine learning. Simulink, a companion product, models dynamic systems with block diagrams.
MATLAB is widely used in engineering and science courses, research labs, and industries such as automotive, aerospace and finance. It requires a paid license (many universities provide one). GNU Octave is free software with largely compatible syntax; it covers the core language and many functions but not MathWorks toolboxes or Simulink.
Install and run Hello, world
Install MATLAB from MathWorks, use MATLAB Online in a browser, or install GNU Octave from octave.org (Windows, macOS, Linux). Code is saved in .m files. A script is a file of commands; you run it by typing its name, without .m, in the Command Window.
% hello.m
disp('Hello, world!')matlab -batch "hello" # MATLAB from a terminal
octave hello.m # GNU Octave
# Hello, world!Comments start with %. A line that ends without a semicolon prints its result, so x = 5 shows x = 5, while x = 5; stays silent.
Variables and basic types
Variables are created by assignment and need no declaration. Numbers are double (64-bit floating point) by default, and even a single number is a 1-by-1 matrix.
| Type | Example | Notes |
|---|---|---|
| double | x = 3.14 | The default numeric type |
| integer types | n = int32(42) | int8 to int64, uint8 to uint64; arithmetic saturates |
| logical | ok = true | Result of comparisons such as x > 2 |
| char array | name = 'Ana' | Single quotes; a row vector of characters |
| string | s = "Ana" | MATLAB string object; Octave treats double quotes as a char array |
| cell array | c = {'Ana', 30} | Holds values of different types |
| struct | p.name = 'Ana' | Named fields |
x = 10;
y = 3;
x / y % 3.3333
mod(x, y) % 1
x ^ 2 % 100
name = 'Ana';
fprintf('%s is %d years old\n', name, 30)
% Ana is 30 years old
class(x) % 'double'Vectors and matrices
Square brackets build arrays: spaces or commas separate columns, semicolons separate rows. Indexing uses parentheses and starts at 1; end means the last index and : means "all".
v = [3 1 4 1 5];
v(1) % 3
v(end) % 5
v(2:4) % [1 4 1]
v * 2 % [6 2 8 2 10]
v(v > 2) % [3 4 5] logical indexing
A = [1 2; 3 4];
A(2, :) % second row: [3 4]
A' % transpose: [1 3; 2 4]
A * A % matrix product: [7 10; 15 22]
A .* A % element-wise: [1 4; 9 16]
b = [5; 11];
x = A \ b % solves A*x = b: [1; 2]
z = zeros(2, 3); % also ones, eye, rand
r = 0:0.25:1; % [0 0.25 0.5 0.75 1]Operators with a dot (.*, ./, .^) work element by element; without the dot they follow the rules of linear algebra. The backslash operator solves linear systems and is more accurate than computing inv(A) * b.
Control flow
score = 85;
if score >= 90
disp('A')
elseif score >= 80
disp('B')
else
disp('C')
end
total = 0;
for k = 1:10
total = total + k;
end
fprintf('total = %d\n', total) % total = 55
n = 3;
while n > 0
n = n - 1;
end
switch 'red'
case {'red', 'green'}
disp('a color')
otherwise
disp('unknown')
endEvery block ends with end. Many loops can be replaced by a vectorized expression: the loop above is the same as sum(1:10), which is shorter and usually faster. If you must build an array in a loop, preallocate it first, for example result = zeros(1, 1000);.
Functions and anonymous functions
A function lives in its own file whose name matches the function name. A function can return several outputs. Scripts can also contain local functions at the end of the file in recent MATLAB versions.
% stats.m
function [m, s] = stats(x)
%STATS Mean and sample standard deviation of a vector.
m = mean(x);
s = std(x);
end[m, s] = stats([2 4 4 5 7]) % m = 4.4000, s = 1.8166
[biggest, where] = max([3 9 2]) % biggest = 9, where = 2
f = @(x) x.^2 + 1; % anonymous function
f(3) % 10
f([1 2 3]) % [2 5 10]
fzero(@(x) x.^2 - 2, 1) % 1.4142, a root near 1
integral(f, 0, 1) % 1.3333Anonymous functions, created with @, are often passed to other functions such as fzero, integral, arrayfun or optimization routines. Write them with element-wise operators (.^) so they also work on vectors.
Structs and cell arrays
person.name = 'Ana';
person.age = 30;
fprintf('%s is %d\n', person.name, person.age) % Ana is 30
c = {'Ana', 30, [1 2 3]}; % cell array with mixed types
c{2} % 30 (curly braces get the content)
class(c(2)) % 'cell' (parentheses get a sub-cell)
names = {'Ana', 'Ben', 'Cleo'};
numel(names) % 3
upper(names{1}) % 'ANA'MATLAB also has a table type for column-oriented data with named variables, similar to a spreadsheet; readtable loads CSV and Excel files into it.
Error handling
Raise an error with error, optionally with an identifier such as 'demo:negative', and handle it with try ... catch. The caught object (an MException in MATLAB) has identifier and message fields.
% safe_sqrt.m
function r = safe_sqrt(x)
if x < 0
error('demo:negative', 'Input must be non-negative, got %g', x);
end
r = sqrt(x);
endtry
safe_sqrt(-4);
catch err
fprintf('%s: %s\n', err.identifier, err.message)
end
% demo:negative: Input must be non-negative, got -4Use warning(...) for problems that should not stop the program. Without the check, sqrt(-4) would not fail at all: it returns the complex number 0 + 2i.
A small complete program: analyze and plot data
% temps.m - analyze a week of temperatures
temps = [21.5 23.0 19.8 25.1 24.3 18.9 22.7];
days = 1:numel(temps);
avg = mean(temps);
[hottest, idx] = max(temps);
above = days(temps > avg);
fprintf('Average: %.2f\n', avg)
fprintf('Hottest: %.1f on day %d\n', hottest, idx)
fprintf('Days above average: %s\n', mat2str(above))
plot(days, temps, '-o')
hold on
plot(days, avg * ones(size(days)), '--')
xlabel('Day'); ylabel('Temperature (C)')
title('Temperatures this week')
legend('Daily', 'Average')
% Average: 22.19
% Hottest: 25.1 on day 4
% Days above average: [2 4 5 7]The script uses logical indexing to find the days above the average without a loop, then draws a line chart with markers and a dashed average line. The same code runs in GNU Octave.
Where to go next
- The MATLAB documentation from MathWorks, starting with the getting-started pages.
- MATLAB Onramp, the free interactive introductory course from MathWorks.
- The GNU Octave manual if you use Octave, including its notes on MATLAB compatibility.
- Learn vectorization,
readtablefor data files and the plotting functions next.
FAQ
Is there a free version of MATLAB?
MATLAB itself needs a license, although MathWorks offers trials and many universities provide campus licenses. GNU Octave is a free, open-source program that runs most basic MATLAB code.
What is the difference between * and .* in MATLAB?
* is matrix multiplication from linear algebra, which requires matching inner dimensions. .* multiplies corresponding elements of two arrays of the same size.
Is GNU Octave fully compatible with MATLAB?
Not fully. Core syntax, matrices, functions and plotting are largely compatible, but Octave lacks MathWorks toolboxes, Simulink and some newer MATLAB features, and it accepts a few extra syntax forms of its own.
Why does MATLAB start indexing at 1?
MATLAB follows mathematical notation, where the first element of a vector or matrix is element 1. Fortran, R and Julia use the same convention.
Should I learn MATLAB or Python?
Learn MATLAB if your course, lab or company uses it, especially with Simulink or specific toolboxes. Python with NumPy, SciPy and Matplotlib is free and more general-purpose, and the concepts transfer between the two.