MATLAB
Matrices, engineering and simulation.
MATLAB (matrix laboratory) is the standard numerical computing environment in engineering and science. It is used to design control systems, process signals and images, run simulations with Simulink and train neural networks with the Deep Learning Toolbox.
Why learn MATLAB?
MATLAB makes matrix maths natural and comes with toolboxes for nearly every engineering field, which is why universities and industry rely on it.
- Matrices first: linear algebra in a few characters.
- Toolboxes: signal processing, control, image processing, deep learning.
- Engineering AI: train networks and deploy them to embedded hardware.
Set up and run your first program
Install MATLAB (a free trial or a university licence) or use MATLAB Online. GNU Octave runs most basic MATLAB code for free.
matlab -batch "hello"
% or: octave hello.mname = "Ada";
fprintf("Hello, AI! Welcome to MATLAB, %s.\n", name);; runs silently; without it MATLAB prints the result.Variables and matrices
Everything is a matrix. Create vectors with [ ] and ranges with start:step:stop. Indexing starts at 1.
layers = 32;
lr = 3e-4;
params = 8.03e9;
fprintf("FP16 size: %.1f GB\n", params * 2 / 1e9);
v = [0.5 -1 2 0.25]; % row vector
x = 0:0.25:1; % range
A = magic(3); % 3x3 matrix
disp(A(2, 3)) % row 2, column 3Matrix and element-wise operations
* is matrix multiplication; .*, ./ and .^ work element by element. This difference is the key to MATLAB.
A = rand(3);
x = rand(3, 1);
y = A * x; % matrix-vector product
s = x .^ 2; % element-wise square
B = A'; % transpose
xs = A \ y; % solve A*xs = y
disp(norm(xs - x)) % close to 0Control flow and functions
if, for, while and switch blocks end with end. Functions can live at the end of a script or in their own file.
for epoch = 1:3
fprintf("epoch %d\n", epoch);
end
bits = 8;
switch bits
case 16, disp("FP16")
case 8, disp("FP8")
otherwise, disp("other")
end
disp(params(32))
function p = params(layers, width)
if nargin < 2, width = 4096; end
p = 12 * layers * width^2;
endTables, structs and plots
Tables hold mixed data like a spreadsheet; structs group named fields. plot makes charts in one line.
gpus = table(["H100"; "H200"; "B200"], [80; 141; 180], 'VariableNames', {'Name', 'VramGB'});
big = gpus(gpus.VramGB > 100, :);
disp(big)
g.name = "RTX 5090"; g.vram = 32; % struct
bar(gpus.VramGB); xticklabels(gpus.Name); ylabel("GB");Vectorisation
Loops are fine, but whole-array operations are shorter and usually faster. Logical indexing selects elements by condition.
x = linspace(-1, 1, 1e6);
tic; y1 = zeros(size(x)); for i = 1:numel(x), y1(i) = x(i)^2; end; t1 = toc;
tic; y2 = x .^ 2; t2 = toc;
fprintf("loop %.3f s, vectorised %.3f s\n", t1, t2);
pos = x(x > 0.9); % logical indexing
disp(numel(pos))AI with MATLAB
MATLAB's Deep Learning Toolbox trains CNNs, LSTMs and transformers, imports models from PyTorch and ONNX, and generates C/CUDA code to deploy them on embedded devices and GPUs. It is popular for AI in signal processing, radar, medical imaging and autonomous systems.
The essential libraries
Gradient descent, vectorised
MATLAB's vector maths makes each update a single line.
x = linspace(-1, 1, 100)';
y = 3*x + 0.5 + 0.1*randn(100, 1);
w = 0; b = 0; lr = 0.1;
for step = 1:500
err = (w*x + b) - y;
w = w - lr * mean(2*err.*x);
b = b - lr * mean(2*err);
end
fprintf("w = %.2f, b = %.2f\n", w, b);
disp(polyfit(x, y, 1)) % built-in fit agreesBuild an AI agent in MATLAB
MathWorks' free add-on "Large Language Models (LLMs) with MATLAB" supports local models through Ollama, including tool (function) calling. Install it from the Add-On Explorer or GitHub.
% Requires the "Large Language Models (LLMs) with MATLAB" add-on
f = openAIFunction("get_weather", "Get the current weather for a city");
f = addParameter(f, "city", type="string", description="City name");
chat = ollamaChat("llama3.1", Tools=f);
messages = messageHistory;
messages = addUserMessage(messages, "Should I take an umbrella in Lahore today?");
[~, msg] = generate(chat, messages);
messages = addResponseMessage(messages, msg);
if isfield(msg, "tool_calls")
call = msg.tool_calls(1);
args = jsondecode(call.function.arguments);
result = "It is 24°C and sunny in " + args.city + ".";
messages = addToolMessage(messages, call.id, call.function.name, result);
[text, ~] = generate(chat, messages);
disp(text)
else
disp(msg.content)
endFunction names follow the add-on's documentation; check its examples for your version.
ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.MATLAB learning roadmap
Tick items off as you go. Your progress is saved in this browser.
Beginner
Intermediate
Advanced
Projects to build
MATLAB cheat sheet
| Task | Syntax |
|---|---|
| Vector | v = [1 2 3]; |
| Range | x = 0:0.1:1; |
| Element-wise | a .* b |
| Matrix multiply | A * B |
| Solve | x = A \ b; |
| Plot | plot(x, y) |
Common mistakes
- Using
*when you meant element-wise.*gives size errors or wrong results. - Indexing starts at 1, and
endmeans the last element. - Growing arrays inside loops is slow; preallocate with
zeros.
Where to go next
- MATLAB Onramp — free course
- MATLAB docs — official
- GNU Octave — free alternative
On TensorCore.si: Julia volume, Python volume.
Keyboard: [ previous language · ] next language · / search the library