Guide
The language
MathLab speaks the MATLAB language. Everything is an array, operations work on whole arrays at once, and you rarely need a loop.
Vectors and matrices
Square brackets build arrays: spaces or commas separate columns, semicolons start a new row. Leave the semicolon off the end of a line to see the result.
a = [1 2 3] % a row vector
b = [1; 2; 3] % a column vector
M = [1 2; 3 4] % a 2×2 matrix
r = 0:0.25:1 % start:step:stop
n = linspace(0, 1, 5)Try it ↗a = 1×3
1 2 3
b = 3×1
1
2
3
M = 2×2
1 2
3 4
r = 1×5
0 0.25 0.5 0.75 1
n = 1×5
0 0.25 0.5 0.75 1Operators
*, / and ^ follow the rules of linear algebra. Put a dot in front (.*, ./, .^) to work element by element — which is what you want for plotting formulas. Arrays of different sizes combine when one is a single value, or a row with a column (implicit expansion).
A = [1 2; 3 4];
A * A % matrix product
A .* A % element by element
A' % transpose
A \ [5; 6] % solve A x = b
x = 1:5;
x.^2 + 1 % powers need the dotTry it ↗ans = 2×2 7 10 15 22 ans = 2×2 1 4 9 16 ans = 2×2 1 3 2 4 ans = 2×1 -4 4.5 ans = 1×5 2 5 10 17 26
Indexing
Round brackets pick elements. end means the last one, : means all, and a condition selects matching elements.
v = [10 20 30 40 50];
v(2) % second element (counting starts at 1)
v(end) % last
v([1 3]) % several
v(v > 25) % logical indexing
M = magic(4);
M(2, :) % second row
M(:, end)' % last column, as a rowTry it ↗ans = 20 ans = 50 ans = 1×2 10 30 ans = 1×3 30 40 50 ans = 1×4 5 11 10 8 ans = 1×4 13 8 12 1
Loops and conditions
if/elseif/else, for, while, switch, break and continue, each closed with end. Compare with ==, ~=, <, and combine with &&, || and ~.
total = 0;
for k = 1:10
if mod(k, 2) == 0
total = total + k; % add the even numbers
end
end
total
n = 27; steps = 0;
while n ~= 1 % the Collatz sequence
if mod(n, 2), n = 3*n + 1; else, n = n/2; end
steps = steps + 1;
end
stepsTry it ↗total = 30 steps = 111
Functions
Anonymous functions (@(x) …) are handy for one-liners and for passing to solvers such as fzero, integral and ode45. Longer functions can be defined anywhere in the script and return several outputs.
f = @(x) x.^2 - 2; % an anonymous function
root = fzero(f, 1)
function [m, s] = stats(x) % your own function, anywhere in the script
m = mean(x);
s = std(x);
end
[m, s] = stats([2 4 4 4 5 5 7 9])Try it ↗root = 1.4142 m = 5 s = 2.1381
Text
Text goes in single quotes. Join pieces with [ ], format numbers with sprintf or num2str, and print with disp or fprintf.
name = 'MathLab';
msg = sprintf('%s has %d letters', name, length(name))
upper(name)
parts = strsplit('a,b,c', ',')
strjoin(parts, ' + ')
contains(name, 'Lab')Try it ↗msg = 'MathLab has 7 letters'
ans = 'MATHLAB'
parts = {'a', 'b', 'c'}
ans = 'a + b + c'
ans = 1Cell arrays and structs
A cell array holds values of different kinds (index it with ); a struct holds named fields (reach them with a dot). Data from webread and readtable arrives in these forms.
c = {'red', [1 2 3], 42}; % a cell array holds anything
c{2} % curly braces give the content
c{4} = 'added';
numel(c)
p = struct('name', 'Ada', 'born', 1815);
p.field = 'mathematics'; % add a field
p
fieldnames(p)Try it ↗ans = 1×3
1 2 3
ans = 4
p = struct
name: 'Ada'
born: 1815
field: 'mathematics'
ans = {'name', 'born', 'field'}Complex numbers
Write 3 + 4i. Square roots and logarithms of negative numbers give complex results, fft returns complex spectra, and roots finds complex roots.
z = 3 + 4i
abs(z), angle(z), conj(z)
sqrt(-9)
roots([1 0 4]) % x² + 4 = 0
exp(1i*pi) + 1 % Euler: (almost) zeroTry it ↗z = 3 + 4i ans = 5 ans = 0.9273 ans = 3 − 4i ans = 3i ans = 2×1 complex 2i -2i ans = 1.2246e-16i
Errors and checks
try … catch err … end handles errors; err.message says what went wrong. error and assert raise your own. When something does go wrong, the console shows the line and, inside functions, the call stack; Debug this error replays the run so you can step back to the cause.
try
x = [1 2 3] + [1 2];
catch err
disp(['Caught: ' err.message])
end
assert(isreal(sqrt(4)), 'should be real')
disp('still running')Try it ↗Caught: Matrix dimensions must agree (1×3 and 1×2) still running
The editor checks your code as you type: unknown names (with a suggested fix), variables used before they are set, missing ends, = where == was meant, and calls with too many arguments.