Ron Bakker/MathLabHelp
Open MathLab ↗

Reference

Function reference

All 508 built-in functions. Click an example to run it in MathLab. In the editor, help name in the console shows the same.

Constants 8 functions

e

Euler's number e = 2.71828… (same as exp(1))

i

i (or j, or 1i)

The imaginary unit √−1. Write complex numbers as 3 + 4i.

z = 3 + 4iTry it ↗

NaN

Not-a-Number (missing or undefined value)

Elementary maths 57 functions

abs

abs(x)

Absolute value; magnitude |z| for complex numbers

abs(3 + 4i)Try it ↗

acosd

acosd(x)

Inverse cosine, in degrees

acosd(30)Try it ↗

acosh

acosh(x)

Inverse hyperbolic cosine

acosh(2)Try it ↗

asind

asind(x)

Inverse sine, in degrees

asind(30)Try it ↗

asinh

asinh(x)

Inverse hyperbolic sine

asinh(0.5)Try it ↗

atan2

atan2(y, x)

Four-quadrant inverse tangent

atan2(1, -1)Try it ↗

atan2d

atan2d(y, x)

Angle of the point (x, y) in degrees, −180 to 180

atan2d(1, -1)Try it ↗

atand

atand(x)

Inverse tangent, in degrees

atand(30)Try it ↗

atanh

atanh(x)

Inverse hyperbolic tangent

atanh(0.5)Try it ↗

cosd

cosd(x)

Cosine of an angle in degrees

cosd(30)Try it ↗

deg2rad

deg2rad(x)

Degrees to radians

deg2rad(30)Try it ↗

erfc

erfc(x)

Complementary error function

erfc(0.5)Try it ↗

exp

exp(x)

Exponential; exp(iθ) = cos θ + i sin θ

exp(1i*pi)Try it ↗

expm1

expm1(x)

eˣ − 1, accurate for small x

expm1(1e-10)Try it ↗

factorial

factorial(x)

n! (via Γ(n+1))

factorial(5)Try it ↗

gamma

gamma(x)

Gamma function Γ(x)

gamma(5)Try it ↗

gcd

gcd(a, b)

Greatest common divisor

gcd(12, 18)Try it ↗

hypot

hypot(a, b)

sqrt(a² + b²) without overflow

hypot(3, 4)Try it ↗

isfinite

isfinite(x)

True where finite

isfinite(0.5)Try it ↗

isnan

isnan(x)

True where NaN

isnan([1 NaN 3])Try it ↗

isprime

isprime(n)

True where n is prime

find(isprime(1:30))Try it ↗

lcm

lcm(a, b)

Least common multiple

lcm(4, 6)Try it ↗

log

log(x)

Natural logarithm; log(−1) = iπ

log(-1)Try it ↗

log10

log10(x)

Base-10 logarithm

log10(1000)Try it ↗

log1p

log1p(x)

log(1 + x), accurate for small x

log1p(1e-10)Try it ↗

mod

mod(a, m)

Modulo (result has the sign of m)

mod(-1, 3)Try it ↗

nchoosek

nchoosek(n, k)

Binomial coefficient

nchoosek(10, 3)Try it ↗

nthroot

nthroot(x, n)

Real n-th root (nthroot(−8, 3) = −2)

nthroot(-27, 3)Try it ↗

power

power(a, b)

Element-wise power, same as a.^b

power(2, 1:5)Try it ↗

primes

primes(n)

All primes up to n

primes(30)Try it ↗

rad2deg

rad2deg(x)

Radians to degrees

rad2deg(30)Try it ↗

rem

rem(a, m)

Remainder after division (sign of a)

rem(-1, 3)Try it ↗

round

round(x) or round(x, n)

Round to nearest (optionally to n decimals)

round(pi, 3)Try it ↗

sign

sign(x)

Sign: -1, 0 or 1

sign([-2 0 5])Try it ↗

sinc

sinc(x)

Normalised sinc: sin(πx)/(πx)

sinc(0.5)Try it ↗

sind

sind(x)

Sine of an angle in degrees (exact zeros at multiples of 180)

sind(30)Try it ↗

sqrt

sqrt(x)

Square root; negative numbers give complex results (sqrt(−4) = 2i)

sqrt(-4)Try it ↗

tand

tand(x)

Tangent of an angle in degrees

tand(30)Try it ↗

Creating arrays 22 functions

cat

cat(dim, A, B, …)

Join arrays along rows (1), columns (2) or pages (3) — cat(3, R, G, B) makes an RGB image

cat(3, ones(2), zeros(2), zeros(2))Try it ↗

circshift

circshift(x, k)

Rotate elements by k positions

circshift(1:5, 2)Try it ↗

diag

diag(v) / diag(A)

Diagonal matrix from a vector, or the diagonal of a matrix

diag([1 2 3])Try it ↗

flip

flip(A, dim)

Reverse the order along dimension 1 (rows, upside down) or 2 (columns, mirror)

flip(1:4)Try it ↗

fliplr

fliplr(A)

Mirror left to right (works on images too)

fliplr([1 2 3])Try it ↗

flipud

flipud(A)

Turn upside down (works on images too)

flipud([1; 2; 3])Try it ↗

linspace

linspace(a, b, n)

n evenly spaced points from a to b (default n = 100)

linspace(0, 1, 5)Try it ↗

logspace

logspace(a, b, n)

n points from 10^a to 10^b, evenly spaced on a log scale

logspace(0, 3, 4)Try it ↗

magic

magic(n)

Magic square: every row, column and diagonal has the same sum (any n ≥ 3; same layout as MATLAB)

magic(4)Try it ↗

meshgrid

[X, Y] = meshgrid(x, y)

Grid matrices from two vectors — the starting point for surf, contour and quiver

[X, Y] = meshgrid(-2:2, -1:1)Try it ↗

ndgrid

[X, Y] = ndgrid(x, y)

Like meshgrid, but x runs down the rows

[X, Y] = ndgrid(1:2, 1:3)Try it ↗

ones

ones(n) / ones(r, c)

Matrix of ones

ones(2)Try it ↗

rand

rand(n) / rand(r, c)

Uniform random numbers in (0, 1). Use rng(seed) to make them repeatable.

rand(1, 5)Try it ↗

randi

randi(max, r, c) / randi([lo hi], r, c)

Random whole numbers

randi(6, 1, 10)Try it ↗

randn

randn(n) / randn(r, c)

Normally distributed random numbers (mean 0, std 1)

mean(randn(1, 1000))Try it ↗

repmat

repmat(A, m, n)

Tile A m×n times

repmat([1 2], 2, 2)Try it ↗

reshape

reshape(A, r, c)

Same elements, new shape (column order)

reshape(1:6, 2, 3)Try it ↗

rng

rng(seed)

Seed the random number generator so results are reproducible

rng(42); randTry it ↗

rot90

rot90(A, k)

Rotate by k × 90° counter-clockwise (works on images too)

rot90([1 2; 3 4])Try it ↗

transpose

transpose(A)

Transpose, same as A'

transpose([1 2 3])Try it ↗

zeros

zeros(n) / zeros(r, c)

Matrix of zeros

zeros(2, 3)Try it ↗

Arrays 9 functions

all

all(A)

True if all elements are non-zero

all([1 1 0])Try it ↗

any

any(A)

True if any element is non-zero

any([0 0 1])Try it ↗

find

find(cond) / find(cond, k)

Indices where the condition is true (non-zero)

find([0 3 0 5])Try it ↗

isempty

isempty(A)

True if A has no elements

isempty([])Try it ↗

length

length(A)

Length of the largest dimension

length(zeros(3, 7))Try it ↗

numel

numel(A)

Number of elements

numel(1:10)Try it ↗

size

[r, c] = size(A) / size(A, dim)

Size of an array

size(ones(2, 5))Try it ↗

sort

[s, i] = sort(x, 'descend')

Sort (ascending by default) and optionally return the original positions

sort([3 1 2], 'descend')Try it ↗

sortrows

sortrows(A, col)

Sort the rows of a matrix by a column (negative = descending)

sortrows([3 1; 1 2; 2 0], 1)Try it ↗

Linear algebra 16 functions

cross

cross(a, b)

Cross product of 3-vectors

cross([1 0 0], [0 1 0])Try it ↗

dot

dot(a, b)

Dot product

dot([1 2 3], [4 5 6])Try it ↗

eig

[V, D] = eig(A) / e = eig(A)

Eigenvalues (and eigenvectors) of a symmetric matrix

[V, D] = eig([2 1; 1 2])Try it ↗

expm

expm(A)

Matrix exponential (scaling and squaring)

expm([0 1; -1 0])Try it ↗

inv

inv(A)

Matrix inverse (A\b is usually better for solving)

inv([2 1; 1 3])Try it ↗

kron

kron(A, B)

Kronecker product

kron(eye(2), [1 2])Try it ↗

linsolve

linsolve(A, b)

Solve A x = b (same as A\b)

linsolve([2 1; 1 3], [3; 5])Try it ↗

norm

norm(v) / norm(v, p) / norm(A, 'fro')

Vector p-norm (default 2), or matrix 2-norm / Frobenius norm

norm([3 4])Try it ↗

null

null(A)

Basis for the null space (vectors x with A x = 0)

null([1 1; 1 1])Try it ↗

pinv

pinv(A)

Pseudo-inverse (least-squares inverse)

pinv([1 2; 3 4; 5 6])Try it ↗

rank

rank(A)

Number of linearly independent rows or columns

rank([1 2; 2 4])Try it ↗

svd

s = svd(A)

Singular values, largest first

svd([3 0; 4 5])Try it ↗

trace

trace(A)

Sum of the diagonal

trace(magic(3))Try it ↗

tril

tril(A)

Lower triangular part

tril(magic(3))Try it ↗

triu

triu(A)

Upper triangular part

triu(magic(3))Try it ↗

Statistics 36 functions

betainc

betainc(x, …)

Regularised incomplete beta function betainc(x, a, b)

betainc(0.5, 2, 3)Try it ↗

boxplot

boxplot(X) / boxplot(X, {'labels'})

Box-and-whisker plot of each column: median, quartiles, 1.5×IQR whiskers and outliers

boxplot([randn(100, 1), 2 + 0.5*randn(100, 1)], {'control', 'treated'})Try it ↗

chi2cdf

chi2cdf(x, …)

Chi-square cumulative probability, chi2cdf(x, k)

chi2cdf(3.84, 1)Try it ↗

chi2inv

chi2inv(x, …)

Inverse of the chi-square distribution, chi2inv(p, k)

chi2inv(0.95, 1)Try it ↗

corrcoef

corrcoef(x, y)

Correlation coefficient matrix of two vectors

corrcoef(1:10, (1:10).^2)Try it ↗

cov

cov(x, y) / cov(X)

Covariance (matrix for several columns)

cov([1 2 3 4], [2 4 5 9])Try it ↗

cummax

cummax(x)

Running maximum

cummax([1 3 2 5 4])Try it ↗

cummin

cummin(x)

Running minimum

cummin([5 3 4 1 2])Try it ↗

cumprod

cumprod(x)

Running product

cumprod(1:5)Try it ↗

fcdf

fcdf(x, …)

F cumulative probability, fcdf(F, d1, d2)

fcdf(3.2, 2, 30)Try it ↗

finv

finv(x, …)

Inverse of the F distribution, finv(p, d1, d2)

finv(0.95, 2, 30)Try it ↗

gammainc

gammainc(x, …)

Regularised lower incomplete gamma function gammainc(x, a)

gammainc(1, 2)Try it ↗

histcounts

[counts, edges] = histcounts(x, nbins)

Count values in equal-width bins

histcounts(randn(1, 100), 5)Try it ↗

kurtosis

kurtosis(x)

Tail heaviness (3 for a normal distribution; financial returns are usually higher)

kurtosis(randn(1, 1000))Try it ↗

max

[m, i] = max(x) / max(a, b)

Largest element (and its position), or element-wise max of two arrays

max([4 9 2])Try it ↗

mean

mean(x) / mean(A, dim)

Average

mean([2 4 9])Try it ↗

median

median(x) / median(A, dim)

Median

median([5 1 9 3])Try it ↗

min

[m, i] = min(x) / min(a, b)

Smallest element (and its position), or element-wise min of two arrays

min([4 9 2])Try it ↗

mode

mode(x)

Most frequent value

mode([1 2 2 3 3 3])Try it ↗

normcdf

normcdf(x, mu, sigma)

Normal cumulative probability

normcdf(1.96)Try it ↗

norminv

norminv(p, mu, sigma)

Inverse of the normal CDF (critical values)

norminv(0.975)Try it ↗

normpdf

normpdf(x, mu, sigma)

Normal probability density

normpdf(0)Try it ↗

prctile

prctile(x, p)

Percentiles (p from 0 to 100)

prctile(1:10, [25 50 75])Try it ↗

prod

prod(x) / prod(A, dim)

Product of elements

prod(1:5)Try it ↗

quantile

quantile(x, p)

Quantiles (p from 0 to 1)

quantile(randn(1, 1000), 0.95)Try it ↗

range

range(x) / range(A, dim)

Largest minus smallest

range([4 9 2])Try it ↗

skewness

skewness(x)

Asymmetry of a distribution (0 for a normal distribution; negative = long left tail, as in crashes)

skewness(randn(1, 1000))Try it ↗

std

std(x) / std(A, dim)

Sample standard deviation

std(randn(1, 1000))Try it ↗

sum

sum(x) / sum(A, dim)

Sum of elements (per column for matrices)

sum(1:100)Try it ↗

tcdf

tcdf(x, …)

Student t cumulative probability, tcdf(t, dof)

tcdf(2.1, 15)Try it ↗

tinv

tinv(x, …)

Inverse of the t distribution, tinv(p, dof) — critical values

tinv(0.975, 15)Try it ↗

tpdf

tpdf(x, …)

Student t density, tpdf(t, dof)

tpdf(0, 5)Try it ↗

var

var(x) / var(A, dim)

Sample variance

var(randn(1, 1000))Try it ↗

zscore

zscore(x)

Standardise: subtract the mean, divide by the standard deviation

zscore([2 4 6])Try it ↗

Calculus 17 functions

conv

conv(a, b)

Convolution (also multiplies polynomials)

conv([1 1], [1 -1])Try it ↗

cumtrapz

cumtrapz(x, y)

Running integral of sampled data

cumtrapz(0:0.5:2, [0 1 2 3 4])Try it ↗

fminbnd

[x, fval] = fminbnd(f, a, b)

Minimum of f on [a, b] (golden-section search)

fminbnd(@(x) (x - 2).^2 + 1, 0, 5)Try it ↗

fminsearch

[x, fval] = fminsearch(f, x0)

Minimum of a function of several variables (Nelder–Mead)

fminsearch(@(p) (p(1)-1).^2 + (p(2)+2).^2, [0 0])Try it ↗

fzero

fzero(f, x0) / fzero(f, [a b])

A root of f near x0 (or inside the bracket [a b])

fzero(@(x) cos(x) - x, 0.5)Try it ↗

gradient

gradient(y, h)

Numerical derivative with central differences (same length as y)

x = 0:0.1:1; gradient(x.^2, x)Try it ↗

integral

integral(f, a, b)

Definite integral of a function (adaptive Simpson rule)

integral(@(x) exp(-x.^2), -Inf, Inf)Try it ↗

integral2

integral2(f, xmin, xmax, ymin, ymax)

Double integral of f(x, y) over a rectangle (Gauss–Legendre)

integral2(@(x, y) x.*y, 0, 1, 0, 2)Try it ↗

interp1

interp1(x, y, xq, 'method')

Interpolate data at new points. Methods: 'linear' (default), 'nearest', 'previous', 'next', 'spline'

interp1([0 1 2 3], [0 1 0 1], 1.5, 'spline')Try it ↗

ode23

[t, y] = ode23(f, [t0 t1], y0)

Same as ode45 in MathLab (adaptive Runge–Kutta)

[t, y] = ode23(@(t, y) -y, [0 2], 1);Try it ↗

ode45

[t, y] = ode45(f, [t0 t1], y0)

Solve the ODE dy/dt = f(t, y) (adaptive Runge–Kutta 4/5). y has one row per time step.

[t, y] = ode45(@(t, y) -y, [0 5], 1);Try it ↗

polyfit

p = polyfit(x, y, n)

Least-squares polynomial fit of degree n (coefficients, highest power first)

polyfit(1:5, [2.1 3.9 6.2 7.8 10.1], 1)Try it ↗

polyval

polyval(p, x)

Evaluate a polynomial (coefficients highest power first)

polyval([1 0 -1], 3)Try it ↗

roots

roots(p)

All roots of a polynomial, including complex ones

roots([1 0 1])Try it ↗

spectrum

[f, A] = spectrum(x, fs)

One-sided amplitude spectrum of a real signal sampled at fs Hz (FFT). MathLab is real-valued, so this replaces abs(fft(x)).

fs = 100; t = 0:1/fs:1; [f, A] = spectrum(sin(2*pi*10*t), fs);Try it ↗

spline

spline(x, y, xq)

Natural cubic spline through the data points

spline(0:3, [0 1 0 1], 1.5)Try it ↗

trapz

trapz(x, y) / trapz(y)

Integral of sampled data (trapezoid rule)

x = linspace(0, pi); trapz(x, sin(x))Try it ↗

Logic & sets 13 functions

and

and(a, b)

Logical and (same as a & b)

and(1, 0)Try it ↗

double

double(x)

Convert to ordinary numbers (uint8 0–255 stays 0–255; use im2double for 0–1)

double('A')Try it ↗

intersect

intersect(a, b)

Values in both sets

intersect([1 2 3], [2 3 4])Try it ↗

isequal

isequal(a, b)

True if two values are identical

isequal([1 2], [1 2])Try it ↗

ismember

[tf, loc] = ismember(a, set)

True where elements of a occur in set; loc gives their position in set (0 if absent). Works for numbers, text and cell arrays of text.

[tf, loc] = ismember([1 5 3], [3 4 5])Try it ↗

logical

logical(x)

Convert to true/false (non-zero is true)

logical([2 0 -1])Try it ↗

nnz

nnz(x)

Number of non-zero elements

nnz([1 0 2 0])Try it ↗

not

not(a)

Logical not (same as ~a)

not([1 0])Try it ↗

or

or(a, b)

Logical or (same as a | b)

or(1, 0)Try it ↗

setdiff

setdiff(a, b)

Values in a but not in b

setdiff(1:5, [2 4])Try it ↗

union

union(a, b)

Values in either set (sorted)

union([1 3], [2 3])Try it ↗

unique

[u, i, j] = unique(x)

Sorted unique values (and where they come from)

unique([3 1 3 2 1])Try it ↗

xor

xor(a, b)

Exclusive or

xor(true, false)Try it ↗

Text 22 functions

char

char(x)

Text: character codes become letters (char(72) = 'H'), a cell of texts is joined, and a symbolic expression is written out

syms x; ['f(x) = ' char(x^2)]Try it ↗

contains

contains(s, pattern)

True if the text contains the pattern

contains('MathLab', 'Lab')Try it ↗

disp

disp(x)

Show a value without its name

disp('hello')Try it ↗

endsWith

endsWith(s, suffix)

True if the text ends with the suffix

endsWith('data.csv', '.csv')Try it ↗

fprintf

fprintf('x = %g\n', x)

Print formatted text to the command window

fprintf('%d squared is %d\n', 4, 16)Try it ↗

int2str

int2str(x)

Round and convert to text

int2str(2.7)Try it ↗

mat2str

mat2str(A)

Matrix as text you can paste back

mat2str([1 2; 3 4])Try it ↗

num2str

num2str(x) / num2str(x, digits)

Number to text

['x = ' num2str(pi, 3)]Try it ↗

regexp

matches = regexp(s, pattern, 'match')

Find matches of a regular expression (cell array of text)

regexp('x=3, y=42', '\d+', 'match')Try it ↗

regexprep

regexprep(s, pattern, replacement)

Replace using a regular expression ($1 refers to groups)

regexprep('a1b22', '\d+', '#')Try it ↗

sprintf

sprintf('%.3f', x)

Formatted text (%d %f %g %e %s, \n for a new line)

sprintf('%.2f and %d', pi, 7)Try it ↗

startsWith

startsWith(s, prefix)

True if the text starts with the prefix

startsWith('MathLab', 'Math')Try it ↗

str2num

str2num(s)

Text to number

str2num('3.5') + 1Try it ↗

strcat

strcat(a, b, …)

Join text

strcat('ab', 'cd')Try it ↗

strcmp

strcmp(a, b)

True if two texts are identical; with a cell array, one answer per cell

strcmp({'a', 'b'}, 'a')Try it ↗

strcmpi

strcmpi(a, b)

Like strcmp, ignoring upper/lower case

strcmpi('MathLab', 'mathlab')Try it ↗

strjoin

strjoin(c, delimiter)

Join a cell array of text

strjoin({'a', 'b'}, '-')Try it ↗

strrep

strrep(s, old, new)

Replace text

strrep('a-b-c', '-', '+')Try it ↗

strsplit

parts = strsplit(s, delimiter)

Split text into a cell array (default delimiter: whitespace)

strsplit('a,b,c', ',')Try it ↗

strtrim

strtrim(s)

Remove leading and trailing spaces

strtrim(' hi ')Try it ↗

Cells & structs 12 functions

arrayfun

arrayfun(f, x) / arrayfun(f, x, 'UniformOutput', false)

Apply a function to each element: numbers back, or a cell array when results are not single numbers

arrayfun(@(k) sprintf('%d%%', k), [10 20], 'UniformOutput', false)Try it ↗

cell

c = cell(n)

An empty cell array with n elements

c = cell(3)Try it ↗

cellfun

cellfun(f, c) / cellfun(f, c, 'UniformOutput', false)

Apply a function to every cell (numbers back, or a cell array)

cellfun(@numel, {'a', 'bcd'})Try it ↗

fieldnames

fieldnames(s)

Names of a struct's fields (cell array)

fieldnames(struct('a', 1, 'b', 2))Try it ↗

getfield

getfield(s, 'name')

Read a field by name

getfield(struct('a', 5), 'a')Try it ↗

iscell

iscell(x)

True for a cell array

iscell({1, 2})Try it ↗

isfield

isfield(s, 'name')

True if a struct has that field

isfield(struct('x', 1), 'x')Try it ↗

isstruct

isstruct(x)

True for a struct

isstruct(5)Try it ↗

num2cell

num2cell(x)

Put each number into its own cell

num2cell([1 2 3])Try it ↗

rmfield

rmfield(s, 'name')

A copy of the struct without that field

rmfield(struct('a', 1, 'b', 2), 'a')Try it ↗

setfield

setfield(s, 'name', v)

A copy of the struct with a field set

s = setfield(struct(), 'a', 1)Try it ↗

struct

struct('name', value, …)

A record with named fields (read with s.name, set with s.name = …)

s = struct('mass', 2); s.speed = 3; sTry it ↗

Complex numbers 6 functions

angle

angle(z)

Phase angle in radians (atan2 of imaginary and real part)

angle(1i)Try it ↗

complex

complex(a, b)

Build a + bi from real and imaginary parts

complex(1, 2)Try it ↗

conj

conj(z)

Complex conjugate

conj(3 + 4i)Try it ↗

isreal

isreal(x)

True if x has no imaginary part

isreal(2i)Try it ↗

Plotting 20 functions

area

area(x, y)

Filled area under a curve

x = 0:0.1:10; area(x, exp(-x/3).*sin(x).^2)Try it ↗

bar

bar(y) / bar(x, y, width)

Bar chart

bar([3 7 2 5])Try it ↗

barh

barh(y) / barh(x, y)

Horizontal bar chart

barh([40 25 20 15]); yticklabels({'Asia', 'Africa', 'Europe', 'Americas'})Try it ↗

errorbar

errorbar(x, y, err) / errorbar(x, y, neg, pos)

Data points with error bars

x = 1:6; errorbar(x, x.^1.5, 0.3 * x)Try it ↗

fill

fill(x, y, color)

Filled polygon

t = linspace(0, 2*pi, 6); fill(cos(t), sin(t), 'r')Try it ↗

fplot

fplot(f, [a b], 'style')

Plot a function over an interval (default [-5 5])

fplot(@(x) sin(x)./x, [-20 20])Try it ↗

histogram

histogram(data, nbins)

Histogram of the values (default 20 bins)

histogram(randn(1, 2000), 40)Try it ↗

loglog

loglog(x, y, …)

Like plot, with a logarithmic x and y axis

x = logspace(0, 3); loglog(x, x.^2)Try it ↗

pie

pie(x) / pie(x, {'labels'})

Pie chart of the shares of x

pie([45 30 15 10], {'Rent', 'Food', 'Travel', 'Other'})Try it ↗

plot

plot(x, y, 'r--o', …)

Lines. Style letters: colour r g b c m y k, line - -- : -., marker o . x + * s d ^ v. Options: 'LineWidth', 'Color', 'DisplayName'.

x = linspace(0, 2*pi); plot(x, sin(x), x, cos(x), '--')Try it ↗

polarplot

polarplot(theta, r, 'style')

Plot in polar coordinates (theta in radians)

th = linspace(0, 2*pi, 400); polarplot(th, cos(4*th))Try it ↗

quiver

quiver(X, Y, U, V, scale)

Vector field arrows (scaled automatically to the grid spacing)

[X, Y] = meshgrid(-2:0.4:2); quiver(X, Y, -Y, X)Try it ↗

scatter

scatter(x, y, size, c, 'filled')

Points. Size in points² (default 36); c can be one colour or a value per point (uses the colormap).

x = randn(1, 200); scatter(x, x + randn(1, 200)/2, 20, x, 'filled')Try it ↗

semilogx

semilogx(x, y, …)

Like plot, with a logarithmic x axis

x = logspace(0, 3); semilogx(x, x.^2)Try it ↗

semilogy

semilogy(x, y, …)

Like plot, with a logarithmic y axis

x = logspace(0, 3); semilogy(x, x.^2)Try it ↗

stairs

stairs(x, y)

Staircase plot: each value holds until the next sample

stairs(0:10, floor((0:10)/3))Try it ↗

stem

stem(x, y)

Discrete samples as stems

n = 0:20; stem(n, 0.8.^n)Try it ↗

text

text(x, y, 'label') / text(x, y, z, 'label')

Put text at a data point

text(1, 0.5, 'peak')Try it ↗

xline

xline(x, 'style', 'label')

Vertical reference line

xline(0, 'k--', 'threshold')Try it ↗

yline

yline(y, 'style', 'label')

Horizontal reference line

yline(1, 'r:', 'limit')Try it ↗

Fields 8 functions

contour

contour(X, Y, Z, n)

Contour lines (n levels, or a list of levels), coloured by the colormap

[X, Y] = meshgrid(linspace(-2, 2, 80)); contour(X, Y, X.*exp(-X.^2 - Y.^2), 12)Try it ↗

contourf

contourf(X, Y, Z, n)

Filled contours with a colorbar

[X, Y] = meshgrid(linspace(-3, 3, 120)); contourf(X, Y, peaks(X, Y), 12)Try it ↗

fcontour

fcontour(f, [xmin xmax ymin ymax], n)

Contours of a function f(x, y)

fcontour(@(x, y) x.^2 - y.^2, [-2 2 -2 2], 14)Try it ↗

fimplicit

fimplicit(f, [xmin xmax ymin ymax])

Plot the curve where f(x, y) = 0

fimplicit(@(x, y) (x.^2 + y.^2 - 1).^3 - x.^2 .* y.^3, [-1.5 1.5 -1.5 1.5])Try it ↗

heatmap

heatmap(Z)

Like imagesc, with a colorbar

heatmap(rand(8))Try it ↗

imagesc

imagesc(Z) / imagesc(x, y, Z)

Show a matrix as a colour image (row 1 at the top)

imagesc(magic(9)); colorbarTry it ↗

pcolor

pcolor(X, Y, C) / pcolor(C)

Coloured grid cells (like imagesc, with y pointing up)

[X, Y] = meshgrid(-2:0.2:2); pcolor(X, Y, X.^2 - Y.^2); colorbarTry it ↗

peaks

Z = peaks(n) / peaks(X, Y)

MATLAB's classic test surface

surf(peaks(40))Try it ↗

3D 8 functions

fmesh

fmesh(f, [xmin xmax ymin ymax], n)

Wireframe of a function f(x, y)

fmesh(@(x, y) x.*exp(-x.^2 - y.^2), [-2 2 -2 2])Try it ↗

fsurf

fsurf(f, [xmin xmax ymin ymax], n)

Surface of a function f(x, y)

fsurf(@(x, y) sin(x).*cos(y), [-pi pi -pi pi])Try it ↗

mesh

mesh(X, Y, Z)

Wireframe surface

[X, Y] = meshgrid(-8:0.5:8); R = sqrt(X.^2 + Y.^2) + eps; mesh(X, Y, sin(R)./R)Try it ↗

plot3

plot3(x, y, z, 'style')

Line in 3D

t = linspace(0, 10*pi, 800); plot3(sin(t), cos(t), t)Try it ↗

scatter3

scatter3(x, y, z, size, c, 'filled')

Points in 3D

z = randn(1, 300); scatter3(randn(1, 300), randn(1, 300), z, 20, z, 'filled')Try it ↗

shading

shading flat / faceted / interp

Surface edges: faceted shows the grid, flat and interp hide it

shading flatTry it ↗

surf

surf(X, Y, Z) / surf(X, Y, Z, C)

Shaded surface coloured by height (or by C). Drag to rotate, scroll to zoom. Options: 'FaceAlpha', 'EdgeColor', 'none'.

[X, Y] = meshgrid(linspace(-3, 3, 50)); surf(X, Y, peaks(X, Y))Try it ↗

view

view(az, el) / view(2) / view(3)

Camera angle for 3D plots, in degrees (default -37.5, 30). view(2) looks straight down.

view(45, 25)Try it ↗

Axes & labels 35 functions

axis

axis equal / tight / auto / ij / xy / axis([xmin xmax ymin ymax])

Axis limits and aspect

axis equalTry it ↗

box

box on / box off

Frame around the plot

box offTry it ↗

cividis

cividis(n)

The cividis colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(cividis)

colormap(cividis)Try it ↗

clim

clim([lo hi])

Fix the colour range

clim([-1 1])Try it ↗

colorbar

colorbar / colorbar off

Show the colour scale

colorbarTry it ↗

colormap

colormap name — viridis, plasma, magma, inferno, cividis, turbo, parula, coolwarm, rb, gray, hot, jet, ocean

Colour scheme for surfaces, images and contours. viridis, cividis and friends are perceptually uniform and print well.

colormap plasmaTry it ↗

coolwarm

coolwarm(n)

The coolwarm colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(coolwarm)

colormap(coolwarm)Try it ↗

gray

gray(n)

The gray colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(gray)

colormap(gray)Try it ↗

grid

grid on / grid off

Grid lines

grid offTry it ↗

hold

hold on / hold off

Keep existing plots when adding new ones

hold onTry it ↗

hot

hot(n)

The hot colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(hot)

colormap(hot)Try it ↗

inferno

inferno(n)

The inferno colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(inferno)

colormap(inferno)Try it ↗

jet

jet(n)

The jet colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(jet)

colormap(jet)Try it ↗

legend

legend('a', 'b', …) / legend off

Legend for the plotted lines (or use 'DisplayName' when plotting)

legend('sin', 'cos')Try it ↗

magma

magma(n)

The magma colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(magma)

colormap(magma)Try it ↗

ocean

ocean(n)

The ocean colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(ocean)

colormap(ocean)Try it ↗

parula

parula(n)

The parula colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(parula)

colormap(parula)Try it ↗

plasma

plasma(n)

The plasma colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(plasma)

colormap(plasma)Try it ↗

sgtitle

sgtitle('text')

One title above all subplots

subplot(1, 2, 1), plot(1:5), subplot(1, 2, 2), plot(5:-1:1), sgtitle('Two views')Try it ↗

subplot

subplot(rows, cols, k)

Several plots in a grid; k counts left to right, top to bottom

subplot(2, 1, 1); plot(1:10); subplot(2, 1, 2); bar(1:5)Try it ↗

subtitle

subtitle('text')

Smaller line under the title

subtitle('γ = 0.2')Try it ↗

title

title('text')

Axes title

title('Damped oscillation')Try it ↗

turbo

turbo(n)

The turbo colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(turbo)

colormap(turbo)Try it ↗

viridis

viridis(n)

The viridis colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(viridis)

colormap(viridis)Try it ↗

xlabel

xlabel('text')

x-axis label

xlabel('time (s)')Try it ↗

xlim

xlim([a b])

x-axis limits

xlim([0 10])Try it ↗

xticklabels

xticklabels({'a', 'b', …})

Text for the x-axis ticks

bar([3 5 2]); xticklabels({'low', 'mid', 'high'})Try it ↗

xticks

xticks([positions])

Where the x-axis ticks go

plot(0:10); xticks(0:2:10)Try it ↗

ylabel

ylabel('text')

y-axis label

ylabel('amplitude')Try it ↗

ylim

ylim([a b])

y-axis limits

ylim([-1 1])Try it ↗

yticklabels

yticklabels({'a', 'b', …})

Text for the y-axis ticks

barh([3 5 2]); yticklabels({'A', 'B', 'C'})Try it ↗

yticks

yticks([positions])

Where the y-axis ticks go

plot(0:10); yticks([0 5 10])Try it ↗

zlabel

zlabel('text')

z-axis label

zlabel('height')Try it ↗

Figure style 15 functions

close

close all

Accepted for compatibility (clears the figure)

close allTry it ↗

colororder

colororder(name) / colororder([r g b; …])

Colours used for successive lines. Names: gem, okabe-ito, tableau, grayscale, rb; or a matrix with one RGB row (0–1) per colour

colororder('tableau'); plot(rand(5, 4))Try it ↗

exportgraphics

exportgraphics(gcf, 'name.png', 'Resolution', 300)

Save the figure as PNG, SVG or PDF (vector SVG with 'ContentType', 'vector'). MathLab offers the file as a download under the figure.

plot(1:10); exportgraphics(gcf, 'figure.pdf', 'Resolution', 300)Try it ↗

figure

figure / figure('Units', 'inches', 'Position', [0 0 w h])

Accepted for compatibility; sizes in inches or centimetres set the export size

figure('Units', 'inches', 'Position', [0 0 3.5 2.5])Try it ↗

fontname

fontname('Times New Roman')

Font for all text in the figure (any font installed on the viewer's computer)

plot(1:10), fontname('Georgia')Try it ↗

fontsize

fontsize(n) / fontsize('increase') / fontsize('decrease')

Font size in points for all text in the figure (11 is normal)

plot(1:10), title('Bigger text'), fontsize(16)Try it ↗

gca

ax = gca

The current axes (for set)

set(gca, 'FontSize', 14)Try it ↗

gcf

f = gcf

The current figure (for set, exportgraphics)

exportgraphics(gcf, 'figure.png', 'Resolution', 300)Try it ↗

opengl

opengl hardware / opengl software / opengl info

Choose how figures are drawn on screen: hardware uses WebGL for 3D surfaces, large scatter plots and globes (the default); software uses the regular renderer. Exports are always drawn the regular, print-quality way.

opengl infoTry it ↗

print

print('-dpng', '-r300', 'name')

Save the figure, MATLAB print style (-dpng, -dsvg, -dpdf, -r<dpi>)

print('-dpdf', '-r600', 'figure')Try it ↗

saveas

saveas(gcf, 'name.png')

Save the figure (PNG, SVG or PDF)

saveas(gcf, 'figure.svg')Try it ↗

set

set(gca, 'Name', value, …) / set(gcf, …)

Change properties. Axes: FontSize, FontName, XGrid, YGrid, Box, XScale, YScale, XDir, YDir, XLim, YLim, XTick, YTick, XTickLabel, YTickLabel, Title, ColorOrder. Figure: Color ('w' or 'k'), Units + Position (export size), Theme.

plot(1:10); set(gca, 'FontSize', 14, 'Box', 'off')Try it ↗

style

style name — default, web, paper, ieee, ieee-wide, nature, thesis, slides, poster, minimal, grayscale, dark, light

Apply a figure style preset (MathLab): fonts, line widths, colours, grid and export size for papers, journals, slides or the web. Put it at the top of the script.

style ieee x = linspace(0, 4*pi); plot(x, sin(x), x, cos(x)), legend('sin', 'cos')Try it ↗

styles

List the figure style presets

theme

theme light / theme dark / theme auto

Background of the figure (as in MATLAB): light, dark, or follow the page

theme darkTry it ↗

Animation 3 functions

animate

animate(seconds) / animate(seconds, fps)

Turn the script into an animation: it re-runs every frame with t = time in seconds (0 … seconds, then loops). Use t anywhere in your code.

animate(4); x = linspace(0, 2*pi); plot(x, sin(x - 2*pi*t/4))Try it ↗

drawnow

Accepted for compatibility (MathLab draws when the script ends)

drawnowTry it ↗

pause

pause(s)

Not supported inside a script — use animate(seconds) and the time variable t instead

animate(5)Try it ↗

Audio 3 functions

audiowrite

audiowrite('name.wav', y, fs)

Make a WAV file of the signal (offered as a download next to the figure)

fs = 22050; t = 0:1/fs:2; audiowrite('tone.wav', 0.4*sin(2*pi*330*t), fs)Try it ↗

sound

sound(y, fs)

Play a signal as sound. y between −1 and 1 (louder values are clipped); fs = samples per second (default 8192). Use an N×2 matrix for stereo.

fs = 44100; t = 0:1/fs:1; sound(0.5*sin(2*pi*440*t), fs)Try it ↗

soundsc

soundsc(y, fs)

Like sound, but scaled so the loudest sample is at full volume

fs = 8192; soundsc(randn(1, fs), fs) % one second of noiseTry it ↗

Signal processing 15 functions

blackman

blackman(n)

Blackman window (column vector) — very low side lobes

blackman(8)'Try it ↗

conv2

C = conv2(A, B, 'full' | 'same' | 'valid')

2-D convolution

conv2([1 2; 3 4], [1 1; 1 1])Try it ↗

downsample

downsample(x, k)

Keep every k-th sample

downsample(1:10, 3)Try it ↗

fft

fft(x) / fft(x, n)

Discrete Fourier transform (complex). Any length; zero-pads or truncates to n. Use abs(fft(x)) for magnitudes.

abs(fft([1 0 0 0]))Try it ↗

fftshift

fftshift(X)

Move the zero frequency to the middle of the spectrum

fftshift(1:6)Try it ↗

filter

y = filter(b, a, x)

Digital filter: a(1) y(n) = Σ b(k) x(n−k+1) − Σ a(k) y(n−k+1). Use a = 1 for FIR filters.

filter(ones(1, 3)/3, 1, [3 6 9 12])Try it ↗

filter2

Y = filter2(h, X, 'same')

2-D correlation (filter2(h, X) = conv2(X, rot90(h, 2), 'same'))

filter2(ones(3)/9, magic(5))Try it ↗

freqz

[H, f] = freqz(b, a, n, fs)

Frequency response of a digital filter (complex H at n frequencies up to fs/2)

[H, f] = freqz(ones(1, 5)/5, 1, 256, 1000);Try it ↗

hamming

hamming(n)

Hamming window (column vector)

hamming(8)'Try it ↗

hann

hann(n)

Hann window (column vector) — reduces spectral leakage

hann(8)'Try it ↗

ifft

ifft(X) / ifft(X, n)

Inverse Fourier transform

real(ifft(fft([1 2 3])))Try it ↗

ifftshift

ifftshift(X)

Undo fftshift

ifftshift(fftshift(1:5))Try it ↗

unwrap

unwrap(phase)

Remove 2π jumps from a phase signal

unwrap([0 3 -3])Try it ↗

upsample

upsample(x, k)

Insert k−1 zeros between samples

upsample([1 2 3], 2)Try it ↗

xcorr

[r, lags] = xcorr(x, y)

Cross-correlation (autocorrelation with one input)

[r, lags] = xcorr([1 2 3 2 1]);Try it ↗

Image processing 48 functions

bwareaopen

BW2 = bwareaopen(BW, P)

Remove regions smaller than P pixels

BW2 = bwareaopen(imbinarize(testimage('blobs')), 200);Try it ↗

bwlabel

[L, n] = bwlabel(BW, conn)

Number the connected regions of a black-and-white image (8-connected by default); L holds the region number of every pixel

[L, n] = bwlabel(imbinarize(testimage('blobs')));Try it ↗

bwperim

P = bwperim(BW)

Outline pixels of the white regions

P = bwperim(imbinarize(testimage('blobs')));Try it ↗

checkerboard

I = checkerboard(n, p, q)

Checkerboard test image: squares of n pixels, 2p × 2q tiles; the light squares on the right half are grey (as in MATLAB)

imshow(checkerboard(20))Try it ↗

edge

BW = edge(I, 'sobel' | 'prewitt' | 'canny' | 'log', threshold)

Find edges (logical image). 'sobel' (default) thresholds the gradient; 'canny' adds smoothing, thinning and hysteresis for clean, connected edges; 'log' finds zero crossings of the Laplacian of Gaussian.

imshow(edge(rgb2gray(testimage('shapes')), 'canny'))Try it ↗

fspecial

h = fspecial('average' | 'gaussian' | 'disk' | 'sobel' | 'prewitt' | 'laplacian' | 'log' | 'motion' | 'unsharp', …)

Ready-made filter kernels for imfilter

h = fspecial('gaussian', 7, 1.5)Try it ↗

graythresh

level = graythresh(I)

Otsu's threshold (0–1) that best separates dark and bright pixels

graythresh(testimage('blobs'))Try it ↗

histeq

J = histeq(I)

Histogram equalisation: spread the grey levels so they are used evenly (more contrast)

J = histeq(rgb2gray(testimage('gradient')) * 0.3);Try it ↗

hsv2rgb

RGB = hsv2rgb(HSV)

Colour image from hue, saturation and value

hsv2rgb(cat(3, 0.6, 1, 1))Try it ↗

im2double

im2double(I)

Image as doubles from 0 to 1 (uint8 is divided by 255)

im2double(uint8([0 128 255]))Try it ↗

im2gray

G = im2gray(I)

Grey version of an image (unchanged if it is already grey)

G = im2gray(testimage('shapes'));Try it ↗

im2uint8

im2uint8(I)

Image as uint8 0–255 (doubles from 0–1 are scaled)

im2uint8([0 0.5 1])Try it ↗

imadjust

J = imadjust(I) / imadjust(I, [lowIn highIn], [lowOut highOut], gamma)

Map grey levels to new values: by default stretch so 1 % of pixels clip at each end. Values are on a 0–1 scale.

J = imadjust(rgb2gray(testimage('shapes')), [0.3 0.9], [0 1]);Try it ↗

imbinarize

BW = imbinarize(I) / imbinarize(I, T) / imbinarize(I, 'adaptive')

Black-and-white image: brighter than T (default Otsu's threshold) is true; 'adaptive' compares each pixel with its neighbourhood

BW = imbinarize(testimage('blobs'));Try it ↗

imclearborder

BW2 = imclearborder(BW)

Remove the white regions that touch the edge of the image

BW2 = imclearborder(imbinarize(testimage('blobs')));Try it ↗

imclose

J = imclose(I, se)

Closing (dilate, then erode): fills small dark gaps

J = imclose(imbinarize(testimage('blobs')), strel('disk', 5));Try it ↗

imcrop

J = imcrop(I, [x y width height])

Cut out a rectangle (x = column, y = row of the top-left corner)

J = imcrop(testimage('shapes'), [130 20 110 100]);Try it ↗

imdilate

J = imdilate(I, se)

Dilation: the maximum of the neighbourhood (grows bright regions)

J = imdilate(imbinarize(testimage('blobs')), strel('disk', 3));Try it ↗

imerode

J = imerode(I, se)

Erosion: each pixel becomes the minimum of its neighbourhood (shrinks bright regions)

J = imerode(imbinarize(testimage('blobs')), strel('disk', 3));Try it ↗

imfill

BW2 = imfill(BW, 'holes')

Fill holes: dark areas completely surrounded by white

BW2 = imfill(edge(rgb2gray(testimage('shapes')), 'canny'), 'holes');Try it ↗

imfilter

J = imfilter(I, h, 'replicate' | 'symmetric' | 'circular', 'conv')

Filter an image with a kernel (correlation, like MATLAB; zero padding unless you choose another), per colour channel; the result keeps the image type

J = imfilter(testimage('noisy'), fspecial('average', 5), 'replicate');Try it ↗

imfinfo

info = imfinfo('photo.jpg')

Size of an imported image (Width, Height, original size if it was scaled down)

info = imfinfo('photo.jpg')Try it ↗

imgaussfilt

J = imgaussfilt(I, sigma)

Gaussian blur (sigma in pixels, default 0.5)

J = imgaussfilt(testimage('shapes'), 4);Try it ↗

imgradient

[Gmag, Gdir] = imgradient(I, 'sobel' | 'prewitt')

Gradient magnitude and direction (degrees, −180 to 180)

imshow(imgradient(rgb2gray(testimage('shapes'))), [])Try it ↗

imgradientxy

[Gx, Gy] = imgradientxy(I, 'sobel' | 'prewitt')

Horizontal and vertical brightness gradients

[Gx, Gy] = imgradientxy(rgb2gray(testimage('shapes')));Try it ↗

imhist

[counts, x] = imhist(I, n)

Histogram of the grey levels (n bins, default 256). Without outputs it draws the histogram.

imhist(rgb2gray(testimage('shapes')))Try it ↗

imnoise

J = imnoise(I, 'gaussian', m, v) / imnoise(I, 'salt & pepper', d) / imnoise(I, 'speckle', v)

Add noise to an image (for testing filters). Uses the random generator (rng makes it repeatable).

J = imnoise(testimage('shapes'), 'salt & pepper', 0.05);Try it ↗

imopen

J = imopen(I, se)

Opening (erode, then dilate): removes small bright specks

J = imopen(imbinarize(testimage('blobs')), strel('disk', 5));Try it ↗

imoverlay

J = imoverlay(I, mask, color)

Paint the pixels where mask is true in one colour (default yellow) — e.g. to show edges on a photo

I = testimage('shapes'); imshow(imoverlay(I, edge(rgb2gray(I)), 'r'))Try it ↗

imread

I = imread('photo.jpg' or 'https://…/image.png')

Read an imported image (PNG, JPEG, GIF, WebP) or one from the web: r×c×3 uint8 for colour, r×c for grey. Photos larger than 1024 pixels are scaled down.

I = imread('photo.jpg'); imshow(I)Try it ↗

imresize

J = imresize(I, scale) / imresize(I, [rows cols], 'nearest' | 'bilinear')

Resize an image (bilinear by default; NaN in [rows cols] keeps the aspect ratio)

J = imresize(testimage('shapes'), 0.5);Try it ↗

imrotate

J = imrotate(I, angle, 'nearest' | 'bilinear', 'loose' | 'crop')

Rotate counter-clockwise by angle degrees; the corners are filled with black

J = imrotate(testimage('shapes'), 30);Try it ↗

imsharpen

J = imsharpen(I, 'Amount', a, 'Radius', r)

Unsharp masking: add back the difference between the image and a blurred copy (Amount 0.8, Radius 1)

J = imsharpen(testimage('shapes'), 'Amount', 1.5);Try it ↗

imshow

imshow(I) / imshow(I, [low high]) / imshow(I, [])

Show an image: grey (r×c) or colour (r×c×3). uint8 runs 0–255, double 0–1; [] stretches the image's own range.

imshow(testimage('shapes'))Try it ↗

imshowpair

imshowpair(A, B) / imshowpair(A, B, 'diff')

Compare two images: side by side ('montage', the default) or their absolute difference ('diff')

I = rgb2gray(testimage('shapes')); imshowpair(I, imgaussfilt(I, 3))Try it ↗

imtile

T = imtile({I1, I2, …})

One image with the given images in a grid

T = imtile({testimage('shapes'), testimage('texture')});Try it ↗

imwrite

imwrite(I, 'name.png')

Save an image as a PNG or JPEG file (offered as a download under the figure)

imwrite(testimage('shapes'), 'shapes.png')Try it ↗

label2rgb

RGB = label2rgb(L)

Colour each labelled region (from bwlabel) differently; label 0 is white

label2rgb(bwlabel(testimage('blobs') > 0.5))Try it ↗

medfilt2

J = medfilt2(I, [m n])

Median filter (default 3×3): removes salt-and-pepper noise while keeping edges sharp

J = medfilt2(imnoise(rgb2gray(testimage('shapes')), 'salt & pepper', 0.05));Try it ↗

montage

montage({I1, I2, …})

Show several images side by side (grey and colour can be mixed)

I = testimage('shapes'); montage({I, rgb2gray(I), edge(rgb2gray(I))})Try it ↗

phantom

P = phantom(n)

The Shepp–Logan head phantom (modified), the standard test image of medical imaging and tomography

imshow(phantom(256))Try it ↗

regionprops

stats = regionprops(BW or L, 'Area', 'Centroid', 'BoundingBox', 'Perimeter', 'Eccentricity', 'EquivDiameter')

Measure each region. MathLab returns one struct whose fields have one row per region: stats.Area is a column, stats.Centroid is n×2 (x, y).

s = regionprops(imbinarize(testimage('blobs')), 'Area', 'Centroid')Try it ↗

rgb2gray

G = rgb2gray(RGB)

Grey image from a colour image (0.299 R + 0.587 G + 0.114 B)

G = rgb2gray(testimage('shapes'));Try it ↗

rgb2hsv

HSV = rgb2hsv(RGB)

Hue, saturation and value (each 0–1) of a colour image

hsv = rgb2hsv(testimage('shapes'));Try it ↗

strel

se = strel('disk', r) / strel('square', w) / strel('rectangle', [m n]) / strel('diamond', r) / strel('line', len, deg)

Structuring element (a small mask) for imerode, imdilate, imopen and imclose

se = strel('disk', 3)Try it ↗

stretchlim

lim = stretchlim(I, tol)

Grey levels that leave out the darkest and brightest tol of pixels (default 1 %), on a 0–1 scale

stretchlim(rgb2gray(testimage('shapes')))Try it ↗

testimage

I = testimage('shapes' | 'blobs' | 'texture' | 'gradient' | 'noisy')

Built-in test images to try things on (MathLab): coloured shapes, blobs to count, stripes, a ramp, and shapes with noise

imshow(testimage('shapes'))Try it ↗

uint8

uint8(x)

Whole numbers from 0 to 255 (the usual type of image pixels). Values are rounded and clipped; arithmetic on uint8 stays in that range.

uint8([-5 12.6 300])Try it ↗

Data import 16 functions

audioread

[y, fs] = audioread('clip.wav')

Read an uploaded WAV file: samples (one column per channel) and the sample rate

[y, fs] = audioread('clip.wav'); sound(y, fs)Try it ↗

fileread

txt = fileread('notes.txt')

The whole file (or web page) as text

txt = fileread('notes.txt')Try it ↗

height

height(T)

Number of rows of a table (or matrix)

height(T)Try it ↗

isfile

isfile('data.csv')

True if that file has been imported

isfile('data.csv')Try it ↗

jsondecode

v = jsondecode(text)

JSON text → MathLab values (objects become structs, lists become arrays or cells)

s = jsondecode('{"a": [1, 2, 3]}')Try it ↗

jsonencode

txt = jsonencode(v)

MathLab value → JSON text

jsonencode(struct('x', [1 2 3]))Try it ↗

load

A = load('data.txt')

Load numbers from an uploaded text/CSV file

A = load('data.txt')Try it ↗

readcell

C = readcell('data.csv')

Read every cell of a CSV file as text (a cell array, row by row)

C = readcell('names.csv')Try it ↗

readlines

lines = readlines('notes.txt')

The lines of a text file (cell array)

lines = readlines('notes.txt')Try it ↗

readmatrix

A = readmatrix('data.csv')

Read the numbers of a CSV/text file as a matrix (header lines and text are skipped; empty cells are NaN)

A = readmatrix('measurements.csv')Try it ↗

readtable

T = readtable('data.csv' or 'https://…')

Read a CSV (or JSON) table: each column becomes a field, T.Year, T.Country… (numbers → column vectors, text → cell arrays)

T = readtable('https://raw.githubusercontent.com/datasets/co2-ppm/main/data/co2-annmean-mlo.csv'); plot(T.Year, T.Mean)Try it ↗

webread

data = webread('https://…')

Read data from the web: JSON becomes structs and arrays, CSV becomes a table, anything else text. The site must allow access from browsers (CORS).

d = webread('https://api.worldbank.org/v2/country/WLD/indicator/SP.POP.TOTL?format=json&per_page=100')Try it ↗

width

width(T)

Number of columns of a table (or matrix)

width(T)Try it ↗

writematrix

writematrix(A, 'out.csv')

Save a matrix as a CSV file (offered as a download)

writematrix(magic(4), 'magic.csv')Try it ↗

writetable

writetable(T, 'out.csv')

Save a table (struct of columns) as a CSV file (offered as a download)

writetable(struct('x', (1:3)', 'y', [4; 5; 6]), 'xy.csv')Try it ↗

Finance 29 functions

amortize

[principal, interest, balance, payment] = amortize(rate, nper, pv)

Loan schedule: how much of each payment repays the loan and how much is interest

[P, I, bal, pay] = amortize(0.04/12, 360, 300000);Try it ↗

blsdelta

[callDelta, putDelta] = blsdelta(price, strike, rate, time, volatility, yield)

Option delta: change in option price per unit change in the stock price

blsdelta(100, 100, 0.03, 1, 0.2)Try it ↗

blsgamma

g = blsgamma(price, strike, rate, time, volatility, yield)

Option gamma (same for calls and puts)

blsgamma(100, 100, 0.03, 1, 0.2)Try it ↗

blsimpv

vol = blsimpv(price, strike, rate, time, value, …, 'Class', 'put')

Implied volatility: the volatility at which Black–Scholes gives the observed option value (calls by default)

blsimpv(100, 105, 0.03, 0.5, 5.2)Try it ↗

blsprice

[call, put] = blsprice(price, strike, rate, time, volatility, yield)

Black–Scholes prices of European call and put options (rate, volatility and dividend yield per year; time in years)

[c, p] = blsprice(100, 105, 0.03, 0.5, 0.25)Try it ↗

blstheta

[callTheta, putTheta] = blstheta(price, strike, rate, time, volatility, yield)

Option theta: price change per year as time passes

blstheta(100, 100, 0.03, 1, 0.2)Try it ↗

blsvega

v = blsvega(price, strike, rate, time, volatility, yield)

Option vega: price change per unit (1.00 = 100 %) change in volatility

blsvega(100, 100, 0.03, 1, 0.2)Try it ↗

bndprice

[price, duration, convexity] = bndprice(yield, coupon, years, freq)

Price of a bond with face value 100 (yield and coupon as annual fractions, coupons freq times a year, default 2), with Macaulay duration (years) and convexity

[p, D] = bndprice(0.04, 0.05, 10)Try it ↗

bndyield

y = bndyield(price, coupon, years, freq)

Yield to maturity of a bond with face value 100 (inverse of bndprice)

bndyield(95, 0.05, 10)Try it ↗

effrr

e = effrr(rate, m)

Effective annual rate of a nominal rate compounded m times a year

effrr(0.05, 12)Try it ↗

frontier

[risk, ret, W] = frontier(expReturn, expCovariance, n)

Efficient frontier of mean–variance portfolios (fully invested, short selling allowed; closed form). W has one row of weights per point.

[risk, ret] = frontier([0.08 0.12 0.1], [0.04 0.01 0; 0.01 0.09 0.02; 0 0.02 0.06], 20);Try it ↗

fvfix

fv = fvfix(rate, nper, pmt)

Future value of a fixed payment saved each period

fvfix(0.05/12, 360, 200)Try it ↗

fvvar

fv = fvvar(cashflows, rate)

Future value (at the last period) of a series of cash flows

fvvar([-100 -100 -100], 0.05)Try it ↗

irr

r = irr(cashflows)

Internal rate of return: the rate where the NPV is zero

irr([-1000 300 400 500])Try it ↗

maxdrawdown

[mdd, peakIdx, troughIdx] = maxdrawdown(prices)

Largest fall from a peak, as a fraction of the peak

maxdrawdown([100 120 90 110 80 130])Try it ↗

movavg

ma = movavg(prices, 'simple' | 'exponential', n)

Trailing moving average used in trading charts (each point uses only past prices)

movavg([10 11 12 13 12 14], 'simple', 3)Try it ↗

movmax

movmax(x, k)

Moving maximum

movmax([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗

movmean

movmean(x, k)

Moving average over a centred window of k samples

movmean([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗

movmin

movmin(x, k)

Moving minimum

movmin([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗

movstd

movstd(x, k)

Moving standard deviation (e.g. rolling volatility)

movstd([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗

movsum

movsum(x, k)

Moving sum over a centred window of k samples

movsum([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗

nomrr

r = nomrr(e, m)

Nominal rate compounded m times a year that gives effective annual rate e

nomrr(0.0512, 12)Try it ↗

payper

pmt = payper(rate, nper, pv, fv)

Fixed payment per period that pays off a loan (annuity formula)

payper(0.04/12, 360, 300000)Try it ↗

portstats

[risk, ret] = portstats(expReturn, expCovariance, weights)

Expected return and risk (standard deviation) of portfolios; weights has one row per portfolio

[risk, ret] = portstats([0.08 0.12], [0.04 0.01; 0.01 0.09], [0.5 0.5])Try it ↗

pvfix

pv = pvfix(rate, nper, pmt)

Present value of a fixed payment received each period

pvfix(0.05, 20, 1000)Try it ↗

pvvar

npv = pvvar(cashflows, rate)

Net present value of cash flows at times 0, 1, 2, … (the first flow is not discounted)

pvvar([-1000 300 400 500], 0.08)Try it ↗

ret2tick

p = ret2tick(returns, start) / ret2tick(r, start, 'Continuous')

Price series from returns (start price default 1)

ret2tick([0.02 -0.03 0.06], 100)Try it ↗

sharpe

sr = sharpe(returns, riskFree)

Sharpe ratio: mean excess return divided by its standard deviation (per period; × sqrt(252) for daily → yearly)

sharpe([0.01 0.02 -0.01 0.03], 0.001)Try it ↗

tick2ret

r = tick2ret(prices) / tick2ret(prices, [], 'Continuous')

Returns from a price series (simple by default, or log returns). Columns are assets.

tick2ret([100 102 99 105])Try it ↗

Optimisation 8 functions

fmincon

[x, fval, exitflag] = fmincon(fun, x0, A, b, Aeq, beq, lb, ub, nonlcon, options)

Minimise a function subject to linear constraints, bounds and nonlinear constraints [c, ceq] = nonlcon(x) with c ≤ 0 and ceq = 0 (augmented Lagrangian + bounded BFGS)

x = fmincon(@(x) 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2, [0; 0], [], [], [], [], [], [], @(x) deal(x(1)^2 + x(2)^2 - 1, []))Try it ↗

fminunc

[x, fval] = fminunc(fun, x0)

Minimise a smooth function without constraints (quasi-Newton BFGS with numerical gradients)

x = fminunc(@(x) (x(1) - 1)^2 + 10*(x(2) - x(1)^2)^2, [-1; 2])Try it ↗

intlinprog

[x, fval, exitflag] = intlinprog(f, intcon, A, b, Aeq, beq, lb, ub)

Mixed-integer linear programming: like linprog, with the variables listed in intcon kept to whole numbers (branch and bound; small problems)

[x, fval] = intlinprog(-[5; 4; 3], 1:3, [2 3 1; 4 1 2; 3 4 2], [5; 11; 8], [], [], zeros(3, 1), [])Try it ↗

linprog

[x, fval, exitflag] = linprog(f, A, b, Aeq, beq, lb, ub)

Linear programming: minimise f'x with A x ≤ b, Aeq x = beq and lb ≤ x ≤ ub (use [] to skip a part). exitflag 1 = optimal, −2 = infeasible, −3 = unbounded.

[x, fval] = linprog(-[3; 5], [1 0; 0 2; 3 2], [4; 12; 18], [], [], [0; 0])Try it ↗

lsqcurvefit

[x, resnorm, residual, exitflag] = lsqcurvefit(fun, x0, xdata, ydata, lb, ub)

Fit the parameters x of y = fun(x, xdata) to data in the least-squares sense (Levenberg–Marquardt, optional bounds)

x = lsqcurvefit(@(p, t) p(1)*exp(-p(2)*t), [1; 1], 0:5, [5 3.1 1.8 1.1 0.7 0.4])Try it ↗

lsqnonlin

[x, resnorm, residual] = lsqnonlin(fun, x0, lb, ub)

Minimise the sum of squares of the vector fun(x) (Levenberg–Marquardt)

x = lsqnonlin(@(x) [x(1) - 1; 10*(x(2) - x(1)^2)], [0; 0])Try it ↗

optimoptions

opts = optimoptions('fmincon', 'Display', 'off', 'MaxIterations', 500, …)

Options for the solvers (MaxIterations, OptimalityTolerance and Display are used; others are accepted)

opts = optimoptions('fmincon', 'Display', 'off')Try it ↗

quadprog

[x, fval, exitflag] = quadprog(H, f, A, b, Aeq, beq, lb, ub)

Quadratic programming: minimise ½ x'Hx + f'x subject to linear constraints and bounds (H should be positive definite). Used for long-only portfolios.

x = quadprog([2 0; 0 2], [-2; -5], [1 2; -1 2], [6; 2], [], [], [0; 0])Try it ↗

Control systems 23 functions

bode

bode(G) / bode(G1, G2, w) / [mag, phase, w] = bode(G)

Bode plot: gain in dB and phase in degrees against frequency (rad/s)

bode(tf(10, [1 2 10]))Try it ↗

dcgain

k = dcgain(G)

Gain at zero frequency (the final value of the step response, if stable)

dcgain(tf(3, [1 2]))Try it ↗

feedback

T = feedback(G, H, sign)

Closed loop G / (1 + G H) (negative feedback; sign +1 for positive). H defaults to 1.

T = feedback(tf(1, [1 1 0]), 1)Try it ↗

impulse

impulse(G) / [y, t] = impulse(G)

Response to a unit impulse

impulse(tf(1, [1 0.6 1]))Try it ↗

isstable

isstable(G)

True if every pole has a negative real part

isstable(tf(1, [1 -1]))Try it ↗

lsim

y = lsim(G, u, t)

Response to any input signal u sampled at times t (equally spaced). Plots when no output is asked for.

t = 0:0.01:10; lsim(tf(1, [1 1]), sin(t), t)Try it ↗

margin

[Gm, Pm, Wcg, Wcp] = margin(G)

Gain margin (as a factor), phase margin (degrees) and the crossover frequencies of the open loop G. Without outputs: a Bode plot with the margins marked.

margin(tf(1, [1 3 3 1]) * 4)Try it ↗

minreal

G = minreal(G)

Cancel matching poles and zeros

minreal(tf([1 1], [1 3 2]))Try it ↗

nyquist

nyquist(G)

Nyquist plot of G(jω) for positive and negative frequencies, with the critical point −1

nyquist(tf(2, [1 2 2 1]))Try it ↗

parallel

G = parallel(G1, G2)

Two systems side by side, outputs added

parallel(tf(1, [1 1]), tf(2, [1 3]))Try it ↗

pid

C = pid(Kp, Ki, Kd, Tf)

PID controller Kp + Ki/s + Kd s/(Tf s + 1) as a transfer function (Tf filters the derivative; default 0)

C = pid(2, 1, 0.5)Try it ↗

piddata

[Kp, Ki, Kd] = piddata(C)

The gains of a controller made by pid or pidtune

[Kp, Ki, Kd] = piddata(pid(1, 2, 3))Try it ↗

pidtune

C = pidtune(G, 'PID' | 'PI' | 'PD' | 'P')

Choose PID gains for the plant G. MathLab minimises the time-weighted error of the closed-loop step (ITAE) with an overshoot penalty, so the gains differ from MATLAB's frequency-based tuner.

C = pidtune(tf(1, [1 3 3 1]), 'PID')Try it ↗

pole

p = pole(G)

Poles (roots of the denominator)

pole(tf(1, [1 2 5]))Try it ↗

pzmap

pzmap(G)

Poles (×) and zeros (○) in the complex plane

pzmap(tf([1 2], [1 2 5]))Try it ↗

rlocus

rlocus(G) / [r, k] = rlocus(G)

Root locus: where the closed-loop poles of feedback(k*G, 1) move as the gain k grows from 0

rlocus(tf(1, [1 3 2 0]))Try it ↗

series

G = series(G1, G2)

Two systems one after the other (G2 G1)

series(tf(1, [1 1]), tf(2, [1 3]))Try it ↗

step

step(G) / step(G1, G2, tfinal) / [y, t] = step(G)

Response to a unit step input (plotted when no outputs are asked for)

step(tf(1, [1 0.6 1]))Try it ↗

stepinfo

S = stepinfo(G)

Step response numbers: RiseTime (10–90 %), SettlingTime (2 %), Overshoot (%), Peak, PeakTime

S = stepinfo(tf(1, [1 0.6 1]))Try it ↗

tf

G = tf(num, den) / s = tf('s')

Transfer function from numerator and denominator coefficients (highest power of s first). With s = tf('s') you can type G = 1/(s^2 + 2*s + 1).

G = tf(1, [1 2 1])Try it ↗

tfdata

[num, den] = tfdata(G)

Coefficients of the numerator and denominator

[n, d] = tfdata(tf(1, [1 2]))Try it ↗

zero

z = zero(G)

Zeros (roots of the numerator)

zero(tf([1 3], [1 2 5]))Try it ↗

zpk

G = zpk(zeros, poles, gain)

Transfer function from zeros, poles (complex values allowed) and a gain

G = zpk([], [-1 -2], 4)Try it ↗

Symbolic maths 21 functions

coeffs

c = coeffs(p, x)

Coefficients of a polynomial, lowest power first (as MATLAB)

syms x; coeffs(3*x^2 + 2*x + 7, x)Try it ↗

collect

collect(expr, x)

Group terms by powers of x

syms x a; collect(a*x + x^2 + 2*a*x, x)Try it ↗

diff

diff(x) / diff(f, x, n)

Differences between neighbouring elements — or, for a symbolic expression, the (n-th) derivative with respect to x

syms x; diff(x^3*sin(x), x)Try it ↗

expand

expand(expr)

Multiply out products and powers

syms x; expand((x + 1)^3)Try it ↗

factor

factor(p)

Factor a polynomial with whole-number coefficients (rational roots)

syms x; factor(x^3 - 6*x^2 + 11*x - 6)Try it ↗

int

int(f, x) / int(f, x, a, b)

Integral: the antiderivative, or the definite integral from a to b. If no closed form is found, a definite integral is computed numerically.

syms x; int(x*exp(x), x)Try it ↗

isAlways

isAlways(eq)

True if an equation holds for many random values of its variables (a numerical check)

syms x; isAlways(sin(x)^2 + cos(x)^2 == 1)Try it ↗

jacobian

J = jacobian([f1; f2], [x, y])

Matrix of partial derivatives

syms x y; jacobian([x^2*y; sin(x) + y], [x, y])Try it ↗

latex

latex(expr)

LaTeX code for an expression (paste it into a paper, or into LabTeX)

syms x; latex(int(1/(1 + x^2), x))Try it ↗

limit

limit(f, x, a) / limit(f, x, Inf) / limit(f, x, a, 'right')

Limit of f as x approaches a (uses L'Hôpital's rule for 0/0 and ∞/∞)

syms x; limit(sin(x)/x, x, 0)Try it ↗

matlabFunction

f = matlabFunction(expr) / matlabFunction(expr, 'Vars', [x y])

Turn a symbolic expression into an ordinary (fast, element-wise) function handle

syms x; f = matlabFunction(x^2 + 1); f(2)Try it ↗

numden

[n, d] = numden(expr)

Numerator and denominator

syms x; [n, d] = numden((x + 1)/(x^2 - 1))Try it ↗

pretty

pretty(expr)

Print an expression

syms x; pretty((x + 1)/(x - 1))Try it ↗

simplify

simplify(expr)

A simpler equivalent form (expands, collects, cancels, and uses sin² + cos² = 1)

syms x; simplify(sin(x)^2 + cos(x)^2 + (x^2 - 1)/(x - 1))Try it ↗

solve

sol = solve(eq, x) / [a, b] = solve([eq1, eq2], [a, b])

Solve equations (write them with ==, or give an expression that should be 0). Exact for degrees 1–2 and linear systems; numbers otherwise.

syms x; solve(x^2 - 5*x + 6 == 0, x)Try it ↗

subs

subs(expr, x, value) / subs(expr, {x, y}, {1, 2})

Substitute values or expressions for variables

syms x; subs(x^2 + 1, x, 3)Try it ↗

sym

x = sym('x') / sym(1/3) / sym([1 2; 3 4])

A symbolic variable, or exact symbolic numbers (decimals become fractions: sym(0.25) = 1/4)

a = sym(1/3) + sym(1/6)Try it ↗

syms

syms x y z

Create symbolic variables (assumptions such as real or positive are accepted and ignored)

syms x yTry it ↗

symvar

symvar(expr)

The symbolic variables in an expression

syms x y; symvar(x*y + 1)Try it ↗

taylor

taylor(f, x, a, 'Order', n)

Taylor polynomial of f around a, up to (not including) order n (default around 0, order 6)

syms x; taylor(exp(x), x, 0, 'Order', 5)Try it ↗

vpa

vpa(expr, digits)

Evaluate to a decimal number (shown with the given number of digits)

vpa(sym(pi), 10)Try it ↗

Econometrics 13 functions

adftest

[h, pValue, stat] = adftest(y)

Augmented Dickey–Fuller test (constant, one lag): h = 1 rejects a unit root, i.e. the series looks stationary. p-values are interpolated from MacKinnon's table.

[h, p] = adftest(cumsum(randn(200, 1)))Try it ↗

arima

Mdl = arima(p, d, q)

An ARIMA(p, d, q) model to estimate: p autoregressive terms, d differences, q moving-average terms

Mdl = arima(1, 1, 1)Try it ↗

autocorr

[acf, lags] = autocorr(y, numLags)

Sample autocorrelation (plotted with 95 % bounds when no output is asked for)

autocorr(randn(200, 1))Try it ↗

estimate

EstMdl = estimate(Mdl, y)

Fit an arima or garch model to data (ARIMA: conditional least squares; GARCH: Gaussian maximum likelihood on the demeaned series)

EstMdl = estimate(arima(1, 0, 0), y)Try it ↗

fitlm

mdl = fitlm(X, y) / fitlm(T, 'y ~ x1 + x2')

Linear regression with an intercept: estimates, standard errors, t statistics, p-values, R² and the F test. Columns of X are predictors; with a table (struct of columns) give a formula.

mdl = fitlm((1:20)', 3 + 2*(1:20)' + randn(20, 1))Try it ↗

forecast

[yF, yMSE] = forecast(EstMdl, h, y)

Forecast h steps ahead (ARIMA: values and mean squared errors; GARCH: conditional variances)

[yF, yMSE] = forecast(EstMdl, 12, y)Try it ↗

garch

Mdl = garch(p, q)

A GARCH(p, q) model of time-varying volatility (p GARCH terms, q ARCH terms)

Mdl = garch(1, 1)Try it ↗

infer

E = infer(EstMdl, y)

Residuals of an estimated ARIMA model, or conditional variances of a GARCH model

v = infer(EstMdl, r)Try it ↗

lbqtest

[h, pValue, stat] = lbqtest(res, 'Lags', L)

Ljung–Box test for leftover autocorrelation in residuals (h = 1 means there is some)

[h, p] = lbqtest(randn(200, 1))Try it ↗

parcorr

[pacf, lags] = parcorr(y, numLags)

Sample partial autocorrelation — the lag where it cuts off suggests the AR order

parcorr(randn(200, 1))Try it ↗

predict

[ypred, yci] = predict(mdl, Xnew)

Predictions of a fitted linear model, with 95 % confidence intervals for the mean

ypred = predict(mdl, [21; 22])Try it ↗

regress

[b, bint, r, rint, stats] = regress(y, X)

Least-squares coefficients with 95 % intervals (include a column of ones in X for an intercept). stats = [R² F p error-variance].

b = regress(y, [ones(size(x)) x])Try it ↗

simulate

y = simulate(Mdl, n)

Simulate a model with known coefficients: arima(…) or garch(…) values set with 'AR', 'MA', 'Constant', 'Variance' (or 'GARCH', 'ARCH') — e.g. simulate(arima('AR', 0.7, 'Constant', 1, 'Variance', 0.5), 200). Uses rng.

y = simulate(arima('AR', 0.7, 'Constant', 1, 'Variance', 0.5), 200)Try it ↗

Mapping 8 functions

countryinfo

info = countryinfo('NLD' or 'Netherlands')

Name, ISO3 code, centre (lat, lon) and bounding box of a country on the map

countryinfo('Netherlands')Try it ↗

countrymap

countrymap(codes, values) / countrymap(codes, values, 'Europe')

Colour countries by a value (a choropleth). codes: ISO3 codes like 'NLD' or country names (a cell array); values: one number each. Uses the colormap; missing countries stay grey. (MathLab)

countrymap({'NLD', 'BEL', 'DEU', 'FRA'}, [18 12 84 68], 'Europe')Try it ↗

deg2km

km = deg2km(deg)

Degrees of arc on the Earth to kilometres (radius 6371 km)

deg2km(1)Try it ↗

distance

d = distance(lat1, lon1, lat2, lon2)

Great-circle distance in degrees of arc (multiply with deg2km for kilometres)

deg2km(distance(52.37, 4.90, 40.71, -74.01))Try it ↗

geobubble

geobubble(lat, lon, sizedata, colordata)

Bubbles on a world map, area proportional to sizedata (largest bubble about 30 points across)

geobubble([35.7 28.6 31.2], [139.7 77.2 121.5], [37 32 29])Try it ↗

geoplot

geoplot(lat, lon, 'style')

Lines on a map (latitude and longitude in degrees). Starts a world map if there is none.

geoplot([52.4 40.7], [4.9 -74], 'r--')Try it ↗

geoscatter

geoscatter(lat, lon, size, color, 'filled')

Points on a map; size in points², color one value per point (coloured with the colormap) or a colour

geoscatter([52.4 48.9 40.4], [4.9 2.4 -3.7], 60, [1 2 3], 'filled')Try it ↗

worldmap

worldmap(region) / worldmap(region, 'robinson' | 'mercator' | 'equirectangular') / worldmap('globe', [lon lat])

A map to draw on: 'World' (Robinson projection), a continent ('Europe', 'Africa', …), a country name, or a globe seen from a longitude/latitude

worldmap('Europe')Try it ↗

Utilities 17 functions

assert

assert(condition, 'message')

Stop with an error if the condition is false

assert(1 + 1 == 2)Try it ↗

class

class(x)

The type of a value

class(pi)Try it ↗

clear

clear / clear x y

Remove variables from the workspace

clear xTry it ↗

deal

[a, b] = deal(x, y)

Copy inputs to outputs (one input → all outputs)

[a, b] = deal(1, 2)Try it ↗

error

error('message')

Stop with an error message

error('Something went wrong')Try it ↗

feval

feval(f, args…)

Call a function value

feval(@sin, pi/2)Try it ↗

format

format long / format short

Show more or fewer digits

format long; piTry it ↗

help

help / help name

List the functions, or explain one

help plotTry it ↗

isa

isa(x, 'double')

Check the type of a value

isa(pi, 'double')Try it ↗

isnumeric

isnumeric(x)

True for numbers and matrices

isnumeric(3)Try it ↗

tic

Start a stopwatch

tic; sum(1:1e6); tocTry it ↗

warning

warning('message')

Show a warning and carry on

warning('Careful')Try it ↗

who

List the variables in the workspace

whos

Variables with their size and type