Skip to content
Volume M · The TensorCore.si Library

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.

Prologue

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.
Prologue

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.

terminal
matlab -batch "hello"
% or: octave hello.m
hello.m
name = "Ada";
fprintf("Hello, AI! Welcome to MATLAB, %s.\n", name);
TipA line ending in ; runs silently; without it MATLAB prints the result.
Chapter 1

Variables and matrices

Everything is a matrix. Create vectors with [ ] and ranges with start:step:stop. Indexing starts at 1.

variables.m
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 3
Chapter 2

Matrix and element-wise operations

* is matrix multiplication; .*, ./ and .^ work element by element. This difference is the key to MATLAB.

operations.m
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 0
Chapter 3

Control 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.

control.m
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;
end
Chapter 4

Tables, structs and plots

Tables hold mixed data like a spreadsheet; structs group named fields. plot makes charts in one line.

data.m
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");
Chapter 5

Vectorisation

Loops are fine, but whole-array operations are shorter and usually faster. Logical indexing selects elements by condition.

vectorize.m
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))
Part II · AI with MATLAB

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

Deep Learning ToolboxDesign, train and import neural networks.
Statistics and ML ToolboxClassic ML: SVMs, trees, clustering.
GPU CoderGenerate CUDA code from MATLAB models.
Large Language Models (LLMs) with MATLABMathWorks add-on for OpenAI, Ollama and Azure models.

Gradient descent, vectorised

MATLAB's vector maths makes each update a single line.

gradient.m
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 agrees
Part III · Build an AI agent

Build 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.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
agent.m
% 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)
end

Function names follow the add-on's documentation; check its examples for your version.

Run it locallyInstall Ollama, run 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.
Part IV · Your path

MATLAB learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Signal filterDesign a low-pass filter and plot the result.
Image classifierFine-tune a pretrained CNN with transfer learning.
Control systemSimulate a PID controller in Simulink.
Reference

MATLAB cheat sheet

TaskSyntax
Vectorv = [1 2 3];
Rangex = 0:0.1:1;
Element-wisea .* b
Matrix multiplyA * B
Solvex = A \ b;
Plotplot(x, y)
Reference

Common mistakes

  • Using * when you meant element-wise .* gives size errors or wrong results.
  • Indexing starts at 1, and end means the last element.
  • Growing arrays inside loops is slow; preallocate with zeros.
Reference

Where to go next

On TensorCore.si: Julia volume, Python volume.

Keyboard: [ previous language · ] next language · / search the library