MATLAB Documentation
Matrix-based numerical computing for engineering, simulations and signal processing.
MATLAB ("MATrix LABoratory") is a language and environment for numerical computing. Everything is a matrix, so maths on whole arrays is short and fast. Engineers and scientists use it for signal and image processing, control systems, simulations (Simulink), data analysis and machine learning. GNU Octave is a free, mostly compatible alternative.
1. Introduction & Installation
- MATLAB: many colleges provide a campus licence — download from mathworks.com. You can also use MATLAB Online in the browser.
- Free alternative: GNU Octave runs most basic MATLAB code.
The desktop has a Command Window (type commands), an Editor (write .m scripts) and a Workspace (see variables).
disp('Hello, Codify!')
Output:
Hello, Codify!
Run a script file myscript.m by typing myscript (or pressing Run). help sum and doc sum open help.
⚠️ Common error:
Undefined function or variable 'myscript'— the file is not in the current folder or on the path.cdto its folder or useaddpath.
2. Basic Syntax
- A statement without a semicolon prints its result; with
;it runs silently. - Comments use
%, blocks%{ ... %};%%starts a runnable code section. - Indexing uses parentheses and starts at 1.
disp(x)prints a value;fprintfprints formatted text (%d,%.2f,%s,\n).
name = 'Asha';
score = 90;
score = score + 5;
fprintf('%s scored %d\n', name, score);
fprintf('Next level at %d points\n', score + 10);
disp(['Name length: ', num2str(length(name))])
Output:
Asha scored 95
Next level at 105 points
Name length: 4
⚠️ Common error: forgetting
;inside loops prints thousands of lines and slows everything down.
3. Variables & Data Types
The default numeric type is double. Other types: single, int8…int64, uint8…uint64, logical, char ('text'), string ("text"), cell arrays, structs and tables.
x = 7;
y = 2;
fprintf('%g %g %g\n', x / y, mod(x, y), x ^ y);
fprintf('%d %d\n', idivide(int32(x), int32(y)), floor(x / y));
c = 'chars'; s = "string";
fprintf('%s | %s | %s\n', class(x), class(c), class(s));
fprintf('%d %d\n', length(c), strlength(s));
v = int8(200);
fprintf('int8(200) saturates to %d\n', v);
fprintf('%s\n', class(true));
fprintf('%g\n', str2double('3.5') * 2);
Output:
3.5 1 49
3 3
double | char | string
5 6
int8(200) saturates to 127
logical
7
idivide on integers rounds toward zero by default ('fix'), and integer types saturate at their limits instead of wrapping.
⚠️ Common error:
'abc'(char array) and"abc"(string) behave differently:['ab' 'cd']joins characters, while"ab" + "cd"joins strings.
4. Matrices & Operators
Create matrices with [ ] — spaces/commas separate columns, semicolons separate rows.
A = [1 2; 3 4];
B = [5 6; 7 8];
disp(mat2str(A * B)) % matrix multiplication
disp(mat2str(A .* B)) % element-wise multiplication
disp(mat2str(A')) % transpose
disp(mat2str(A .^ 2)) % element-wise power
fprintf('%g\n', det(A)) % determinant
disp(mat2str(inv(A), 4)) % inverse (rounded to 4 significant digits)
x = A \ [5; 11]; % solve A*x = b
disp(mat2str(x, 4))
Output:
[19 22;43 50]
[5 12;21 32]
[1 3;2 4]
[1 4;9 16]
-2
[-2 1;1.5 -0.5]
[1;2]
| Operator | Meaning |
|---|---|
+ - |
add/subtract (element-wise) |
* / ^ |
matrix multiply / divide / power |
.* ./ .^ |
element-wise multiply / divide / power |
' |
transpose |
\ |
solve linear systems (A\b) |
== ~= < > <= >= |
comparison (returns logical arrays) |
| `& | ~` / `&& |
⚠️ Common error:
Incorrect dimensions for matrix multiplication— you used*where you meant.*(element-wise).
5. Conditional Statements
marks = 82;
if marks >= 90
grade = 'A';
elseif marks >= 75
grade = 'B';
else
grade = 'C';
end
fprintf('Grade %s\n', grade);
day = "sat";
switch day
case {"sat", "sun"}
disp('Weekend')
otherwise
disp('Weekday')
end
Output:
Grade B
Weekend
~= means "not equal". Conditions on arrays are true only if all elements are non-zero — use any()/all() to be explicit.
6. Loops & Vectorisation
total = 0;
for i = 1:5
total = total + i^2;
end
fprintf('sum of squares = %d\n', total);
n = 1;
while n < 100
n = n * 3;
end
fprintf('n = %d\n', n);
for k = 10:-3:1
fprintf('%d ', k);
end
fprintf('\n');
% Vectorised: no loop needed
v = 1:5;
fprintf('%d\n', sum(v.^2));
Output:
sum of squares = 55
n = 243
10 7 4 1
55
MATLAB is fastest when you work on whole arrays (vectorisation). If you must grow an array in a loop, pre-allocate it with zeros(1, n) first.
7. Functions
Functions live in their own file (area_circle.m) or at the end of a script.
r = circle_stats(2);
fprintf('area %.2f, perimeter %.2f\n', r.area, r.perimeter);
[lo, hi] = min_max([4 -2 9 3]);
fprintf('%d %d\n', lo, hi);
sq = @(x) x.^2; % anonymous function
fprintf('%s\n', mat2str(sq([1 2 3])));
function s = circle_stats(radius)
s.area = pi * radius^2;
s.perimeter = 2 * pi * radius;
end
function [lo, hi] = min_max(v) % multiple outputs
lo = min(v);
hi = max(v);
end
Output:
area 12.57, perimeter 12.57
-2 9
[1 4 9]
nargin gives the number of inputs passed — use it for default arguments, or the newer arguments block for validation.
8. Arrays, Indexing & Data Structures
v = [10 20 30 40 50];
fprintf('%d %d %s %s\n', v(1), v(end), mat2str(v(2:4)), mat2str(v(v > 25)));
v(2) = []; % delete an element
fprintf('%s numel=%d\n', mat2str(v), numel(v));
M = magic(3);
fprintf('%s | row2 %s | col3 %s | size %s\n', mat2str(M), mat2str(M(2, :)), mat2str(M(:, 3)'), mat2str(size(M)));
fprintf('%s %s\n', mat2str(sum(M)), mat2str(sort([3 1 2], 'descend')));
fprintf('%s %s %s\n', mat2str(zeros(1, 3)), mat2str(ones(2, 1)), mat2str(linspace(0, 1, 5)));
student.name = "Neha"; % struct
student.marks = [85 92 78];
fprintf('%s average %.1f\n', student.name, mean(student.marks));
c = {42, 'text', [1 2 3]}; % cell array holds mixed types
fprintf('%s %s\n', class(c{2}), mat2str(c{3}));
Output:
10 50 [20 30 40] [30 40 50]
[10 30 40 50] numel=4
[8 1 6;3 5 7;4 9 2] | row2 [3 5 7] | col3 [6 7 2] | size [3 3]
[15 15 15] [3 2 1]
[0 0 0] [1;1] [0 0.25 0.5 0.75 1]
Neha average 85.0
char [1 2 3]
Tables hold column data like a spreadsheet:
T = table(["Asha"; "Ravi"; "Neha"], [91; 78; 85], 'VariableNames', {'Name', 'Marks'});
T = sortrows(T, 'Marks', 'descend');
fprintf('%s %d\n', T.Name(1), T.Marks(1));
fprintf('%.2f\n', mean(T.Marks));
Asha 91
84.67
⚠️ Common error:
Index exceeds the number of array elements— indexing starts at 1 andendis the last index;v(0)is always an error.
9. Object-Oriented Programming
MATLAB supports classes in classdef files (Account.m):
classdef Account < handle % handle = reference semantics (shared object)
properties
Owner string
Balance double = 0
end
methods
function obj = Account(owner)
obj.Owner = owner;
end
function deposit(obj, amount)
if amount <= 0
error('Account:invalid', 'Amount must be positive');
end
obj.Balance = obj.Balance + amount;
end
end
end
acc = Account("Asha");
acc.deposit(500);
fprintf('%s %d\n', acc.Owner, acc.Balance);
Asha 500
Classes that don't derive from handle are value classes — methods must return the modified object (obj = deposit(obj, 50)).
10. Advanced Concepts
Plotting:
x = linspace(0, 2*pi, 200);
plot(x, sin(x), 'b-', x, cos(x), 'r--', 'LineWidth', 1.5);
title('Sine and cosine'); xlabel('x (radians)'); ylabel('value');
legend('sin', 'cos'); grid on;
saveas(gcf, 'waves.png');
figure; histogram(randn(1000, 1), 30); % distribution
figure; [X, Y] = meshgrid(-2:0.1:2); surf(X, Y, X.*exp(-X.^2 - Y.^2)); % 3-D surface
Numerical computing:
p = [1 -3 2]; % x^2 - 3x + 2
fprintf('roots: %s\n', mat2str(sort(roots(p))', 4));
f = @(x) x.^2 - 2;
fprintf('fzero: %.4f\n', fzero(f, 1)); % solve f(x) = 0 near 1
fprintf('integral: %.4f\n', integral(@(x) x.^2, 0, 3));
coeffs = polyfit([1 2 3 4], [2 4 6 8], 1); % fit a straight line
fprintf('slope %.1f intercept %.1f\n', coeffs(1), abs(coeffs(2)));
roots: [1 2]
fzero: 1.4142
integral: 9.0000
slope 2.0 intercept 0.0
Simulations — solve differential equations with ode45 (e.g. a falling object or a population model):
dydt = @(t, y) -0.5 * y; % exponential decay
[t, y] = ode45(dydt, [0 10], 100);
fprintf('y(10) ≈ %.2f\n', y(end)); % exact: 100*exp(-5) = 0.67
Errors and files:
try
error('Codify:demo', 'Something failed: %d', 42);
catch err
fprintf('%s | %s\n', err.identifier, err.message);
end
writematrix(magic(3), 'm.csv');
fprintf('%s\n', mat2str(readmatrix('m.csv')));
delete('m.csv');
Codify:demo | Something failed: 42
[8 1 6;3 5 7;4 9 2]
Toolboxes add domain features: Signal Processing, Image Processing, Control System, Statistics and Machine Learning, Deep Learning, and Simulink for block-diagram simulations.
11. Examples with Output
Example 1 — Mean, median and standard deviation
marks = [91 78 85 66 92];
fprintf('mean %.1f median %d std %.2f\n', mean(marks), median(marks), std(marks));
fprintf('above mean: %s\n', mat2str(marks(marks > mean(marks))));
mean 82.4 median 85 std 10.74
above mean: [91 85 92]
Example 2 — Fibonacci with a pre-allocated array
n = 10;
f = zeros(1, n);
f(1:2) = 1;
for k = 3:n
f(k) = f(k-1) + f(k-2);
end
disp(mat2str(f))
[1 1 2 3 5 8 13 21 34 55]
Example 3 — Solve a system of equations
% 2x + y = 5 and x - y = 1
A = [2 1; 1 -1];
b = [5; 1];
sol = A \ b;
fprintf('x = %g, y = %g\n', sol(1), sol(2));
x = 2, y = 1
12. Practice Problems
- Create a 5×5 matrix of random integers between 1 and 100 and find its maximum and its position.
- Compute the sum of all even numbers from 1 to 1000 without a loop.
- Write a function
is_prime(n)and list the primes below 100. - Plot
y = x^2andy = 2^xfor x from 0 to 5 on the same graph with a legend. - Solve a 3×3 system of linear equations with
\. - Load a CSV of temperatures, compute the monthly average and plot it.
- Simulate a ball thrown upward (
ode45) and find when it hits the ground. - Implement a
Stackclass (handle class) withpush,popandisEmpty.
13. Interview Questions
1. What is the difference between * and .*?
* is matrix multiplication (rows × columns); .* multiplies element by element (same-sized arrays).
2. Why is vectorisation preferred? Operations on whole arrays run in optimised compiled code, so they're much faster and shorter than explicit loops.
3. What is a cell array vs a struct vs a table? A cell array holds mixed-type items by index; a struct groups named fields; a table stores column-oriented data with variable names.
4. Script vs function? Scripts run in the base workspace and share its variables; functions have their own workspace, inputs and outputs.
5. Handle vs value classes? Handle objects are passed by reference (changes are shared); value objects are copied, so methods must return the modified object.
6. How do you solve Ax = b?
x = A \ b (left division) — more accurate and faster than inv(A) * b.
7. What does pre-allocation mean?
Creating an array of the final size (zeros(1, n)) before filling it, avoiding repeated memory reallocation in loops.
8. What is an anonymous function?
A one-line function stored in a variable: f = @(x) x.^2;.
9. How does MATLAB index arrays?
1-based, with (row, col) parentheses, end for the last index, : for "all", and logical masks (v(v > 0)).
10. What is Simulink? A graphical environment for modelling and simulating dynamic systems with block diagrams (control systems, signals, embedded code generation).
14. Cheat Sheet & References
Basics
% variables, output, help
x = 5; y = [1 2 3]; z = [1; 2; 3]; s = "text"; c = 'chars';
disp(x); fprintf('%d items, %.2f avg\n', n, avg); num2str(3.14); str2double('2.5')
help plot; doc plot; clc; clear; close all; whos
Matrices
A = [1 2; 3 4]; A'; A * B; A .* B; A \ b; inv(A); det(A); eig(A)
zeros(2, 3); ones(3); eye(3); rand(2); randi(10, 1, 5); magic(4); linspace(0, 1, 5)
size(A); numel(A); length(v); reshape(v, 2, 3); [A, B]; [A; B]
A(2, :); A(:, end); v(v > 2); find(v == 3); sum(A); mean(A, 2); max(v); sort(v)
Control flow and functions
if x > 0, disp('pos'); elseif x == 0, disp('zero'); else, disp('neg'); end
for i = 1:10, end; while cond, end
switch s, case "a", disp(1); otherwise, disp(0); end
f = @(x) x.^2 + 1; f(3)
function out = myfun(a, b), out = a + b; end
Data and files
st.name = "A"; st.marks = [1 2]; c = {1, 'a'}; c{2}
T = readtable('data.csv'); T.Marks; writetable(T, 'out.csv')
M = readmatrix('m.csv'); writematrix(M, 'm.csv'); save('ws.mat'); load('ws.mat')
Plotting and numerics
plot(x, y, 'r--'); hold on; xlabel('x'); ylabel('y'); title('t'); legend('a'); grid on
subplot(2, 1, 1); bar(v); histogram(v); scatter(x, y); surf(X, Y, Z)
roots([1 -3 2]); polyfit(x, y, 1); polyval(p, x); integral(f, 0, 1); fzero(f, 1)
[t, y] = ode45(@(t, y) -y, [0 5], 1);
Official documentation