e
Euler's number e = 2.71828… (same as exp(1))
e^2Try it ↗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.
Euler's number e = 2.71828… (same as exp(1))
e^2Try it ↗Floating-point precision, 2.2e-16
epsTry it ↗Logical 0
flag = falseTry it ↗i (or j, or 1i)The imaginary unit √−1. Write complex numbers as 3 + 4i.
z = 3 + 4iTry it ↗Infinity
1/0 == InfTry it ↗Not-a-Number (missing or undefined value)
0/0Try it ↗π = 3.14159…
area = pi * r^2Try it ↗Logical 1
flag = trueTry it ↗abs(x)Absolute value; magnitude |z| for complex numbers
abs(3 + 4i)Try it ↗acos(x)Inverse cosine
acos(0.5)Try it ↗acosd(x)Inverse cosine, in degrees
acosd(30)Try it ↗acosh(x)Inverse hyperbolic cosine
acosh(2)Try it ↗asin(x)Inverse sine
asin(0.5)Try it ↗asind(x)Inverse sine, in degrees
asind(30)Try it ↗asinh(x)Inverse hyperbolic sine
asinh(0.5)Try it ↗atan(x)Inverse tangent
atan(0.5)Try it ↗atan2(y, x)Four-quadrant inverse tangent
atan2(1, -1)Try it ↗atan2d(y, x)Angle of the point (x, y) in degrees, −180 to 180
atan2d(1, -1)Try it ↗atand(x)Inverse tangent, in degrees
atand(30)Try it ↗atanh(x)Inverse hyperbolic tangent
atanh(0.5)Try it ↗cbrt(x)Cube root
cbrt(-27)Try it ↗ceil(x)Round up
ceil(2.1)Try it ↗cos(x)Cosine (radians)
cos(pi/3)Try it ↗cosd(x)Cosine of an angle in degrees
cosd(30)Try it ↗cosh(x)Hyperbolic cosine
cosh(1)Try it ↗cot(x)Cotangent
cot(0.5)Try it ↗csc(x)Cosecant
csc(0.5)Try it ↗deg2rad(x)Degrees to radians
deg2rad(30)Try it ↗erf(x)Error function
erf(1)Try it ↗erfc(x)Complementary error function
erfc(0.5)Try it ↗exp(x)Exponential; exp(iθ) = cos θ + i sin θ
exp(1i*pi)Try it ↗expm1(x)eˣ − 1, accurate for small x
expm1(1e-10)Try it ↗factorial(x)n! (via Γ(n+1))
factorial(5)Try it ↗fix(x)Round toward zero
fix(-2.7)Try it ↗floor(x)Round down
floor(2.7)Try it ↗gamma(x)Gamma function Γ(x)
gamma(5)Try it ↗gcd(a, b)Greatest common divisor
gcd(12, 18)Try it ↗hypot(a, b)sqrt(a² + b²) without overflow
hypot(3, 4)Try it ↗isfinite(x)True where finite
isfinite(0.5)Try it ↗isinf(x)True where ±Inf
isinf(0.5)Try it ↗isnan(x)True where NaN
isnan([1 NaN 3])Try it ↗isprime(n)True where n is prime
find(isprime(1:30))Try it ↗lcm(a, b)Least common multiple
lcm(4, 6)Try it ↗log(x)Natural logarithm; log(−1) = iπ
log(-1)Try it ↗log10(x)Base-10 logarithm
log10(1000)Try it ↗log1p(x)log(1 + x), accurate for small x
log1p(1e-10)Try it ↗log2(x)Base-2 logarithm
log2(1024)Try it ↗mod(a, m)Modulo (result has the sign of m)
mod(-1, 3)Try it ↗nchoosek(n, k)Binomial coefficient
nchoosek(10, 3)Try it ↗nthroot(x, n)Real n-th root (nthroot(−8, 3) = −2)
nthroot(-27, 3)Try it ↗power(a, b)Element-wise power, same as a.^b
power(2, 1:5)Try it ↗primes(n)All primes up to n
primes(30)Try it ↗rad2deg(x)Radians to degrees
rad2deg(30)Try it ↗rem(a, m)Remainder after division (sign of a)
rem(-1, 3)Try it ↗round(x) or round(x, n)Round to nearest (optionally to n decimals)
round(pi, 3)Try it ↗sec(x)Secant
sec(0.5)Try it ↗sign(x)Sign: -1, 0 or 1
sign([-2 0 5])Try it ↗sin(x)Sine (radians)
sin(pi/6)Try it ↗sinc(x)Normalised sinc: sin(πx)/(πx)
sinc(0.5)Try it ↗sind(x)Sine of an angle in degrees (exact zeros at multiples of 180)
sind(30)Try it ↗sinh(x)Hyperbolic sine
sinh(1)Try it ↗sqrt(x)Square root; negative numbers give complex results (sqrt(−4) = 2i)
sqrt(-4)Try it ↗tan(x)Tangent (radians)
tan(0.5)Try it ↗tand(x)Tangent of an angle in degrees
tand(30)Try it ↗tanh(x)Hyperbolic tangent
tanh(0.5)Try it ↗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(x, k)Rotate elements by k positions
circshift(1:5, 2)Try it ↗diag(v) / diag(A)Diagonal matrix from a vector, or the diagonal of a matrix
diag([1 2 3])Try it ↗eye(n)Identity matrix
eye(3)Try it ↗flip(A, dim)Reverse the order along dimension 1 (rows, upside down) or 2 (columns, mirror)
flip(1:4)Try it ↗fliplr(A)Mirror left to right (works on images too)
fliplr([1 2 3])Try it ↗flipud(A)Turn upside down (works on images too)
flipud([1; 2; 3])Try it ↗linspace(a, b, n)n evenly spaced points from a to b (default n = 100)
linspace(0, 1, 5)Try it ↗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(n)Magic square: every row, column and diagonal has the same sum (any n ≥ 3; same layout as MATLAB)
magic(4)Try it ↗[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 ↗[X, Y] = ndgrid(x, y)Like meshgrid, but x runs down the rows
[X, Y] = ndgrid(1:2, 1:3)Try it ↗ones(n) / ones(r, c)Matrix of ones
ones(2)Try it ↗rand(n) / rand(r, c)Uniform random numbers in (0, 1). Use rng(seed) to make them repeatable.
rand(1, 5)Try it ↗randi(max, r, c) / randi([lo hi], r, c)Random whole numbers
randi(6, 1, 10)Try it ↗randn(n) / randn(r, c)Normally distributed random numbers (mean 0, std 1)
mean(randn(1, 1000))Try it ↗repmat(A, m, n)Tile A m×n times
repmat([1 2], 2, 2)Try it ↗reshape(A, r, c)Same elements, new shape (column order)
reshape(1:6, 2, 3)Try it ↗rng(seed)Seed the random number generator so results are reproducible
rng(42); randTry it ↗rot90(A, k)Rotate by k × 90° counter-clockwise (works on images too)
rot90([1 2; 3 4])Try it ↗transpose(A)Transpose, same as A'
transpose([1 2 3])Try it ↗zeros(n) / zeros(r, c)Matrix of zeros
zeros(2, 3)Try it ↗all(A)True if all elements are non-zero
all([1 1 0])Try it ↗any(A)True if any element is non-zero
any([0 0 1])Try it ↗find(cond) / find(cond, k)Indices where the condition is true (non-zero)
find([0 3 0 5])Try it ↗isempty(A)True if A has no elements
isempty([])Try it ↗length(A)Length of the largest dimension
length(zeros(3, 7))Try it ↗numel(A)Number of elements
numel(1:10)Try it ↗[r, c] = size(A) / size(A, dim)Size of an array
size(ones(2, 5))Try it ↗[s, i] = sort(x, 'descend')Sort (ascending by default) and optionally return the original positions
sort([3 1 2], 'descend')Try it ↗sortrows(A, col)Sort the rows of a matrix by a column (negative = descending)
sortrows([3 1; 1 2; 2 0], 1)Try it ↗cross(a, b)Cross product of 3-vectors
cross([1 0 0], [0 1 0])Try it ↗det(A)Determinant
det([1 2; 3 4])Try it ↗dot(a, b)Dot product
dot([1 2 3], [4 5 6])Try it ↗[V, D] = eig(A) / e = eig(A)Eigenvalues (and eigenvectors) of a symmetric matrix
[V, D] = eig([2 1; 1 2])Try it ↗expm(A)Matrix exponential (scaling and squaring)
expm([0 1; -1 0])Try it ↗inv(A)Matrix inverse (A\b is usually better for solving)
inv([2 1; 1 3])Try it ↗kron(A, B)Kronecker product
kron(eye(2), [1 2])Try it ↗linsolve(A, b)Solve A x = b (same as A\b)
linsolve([2 1; 1 3], [3; 5])Try it ↗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(A)Basis for the null space (vectors x with A x = 0)
null([1 1; 1 1])Try it ↗pinv(A)Pseudo-inverse (least-squares inverse)
pinv([1 2; 3 4; 5 6])Try it ↗rank(A)Number of linearly independent rows or columns
rank([1 2; 2 4])Try it ↗s = svd(A)Singular values, largest first
svd([3 0; 4 5])Try it ↗trace(A)Sum of the diagonal
trace(magic(3))Try it ↗tril(A)Lower triangular part
tril(magic(3))Try it ↗triu(A)Upper triangular part
triu(magic(3))Try it ↗betainc(x, …)Regularised incomplete beta function betainc(x, a, b)
betainc(0.5, 2, 3)Try it ↗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(x, …)Chi-square cumulative probability, chi2cdf(x, k)
chi2cdf(3.84, 1)Try it ↗chi2inv(x, …)Inverse of the chi-square distribution, chi2inv(p, k)
chi2inv(0.95, 1)Try it ↗corrcoef(x, y)Correlation coefficient matrix of two vectors
corrcoef(1:10, (1:10).^2)Try it ↗cov(x, y) / cov(X)Covariance (matrix for several columns)
cov([1 2 3 4], [2 4 5 9])Try it ↗cummax(x)Running maximum
cummax([1 3 2 5 4])Try it ↗cummin(x)Running minimum
cummin([5 3 4 1 2])Try it ↗cumprod(x)Running product
cumprod(1:5)Try it ↗cumsum(x)Running total
cumsum(1:5)Try it ↗fcdf(x, …)F cumulative probability, fcdf(F, d1, d2)
fcdf(3.2, 2, 30)Try it ↗finv(x, …)Inverse of the F distribution, finv(p, d1, d2)
finv(0.95, 2, 30)Try it ↗gammainc(x, …)Regularised lower incomplete gamma function gammainc(x, a)
gammainc(1, 2)Try it ↗[counts, edges] = histcounts(x, nbins)Count values in equal-width bins
histcounts(randn(1, 100), 5)Try it ↗iqr(x)Interquartile range
iqr(1:10)Try it ↗kurtosis(x)Tail heaviness (3 for a normal distribution; financial returns are usually higher)
kurtosis(randn(1, 1000))Try it ↗[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(x) / mean(A, dim)Average
mean([2 4 9])Try it ↗median(x) / median(A, dim)Median
median([5 1 9 3])Try it ↗[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(x)Most frequent value
mode([1 2 2 3 3 3])Try it ↗normcdf(x, mu, sigma)Normal cumulative probability
normcdf(1.96)Try it ↗norminv(p, mu, sigma)Inverse of the normal CDF (critical values)
norminv(0.975)Try it ↗normpdf(x, mu, sigma)Normal probability density
normpdf(0)Try it ↗prctile(x, p)Percentiles (p from 0 to 100)
prctile(1:10, [25 50 75])Try it ↗prod(x) / prod(A, dim)Product of elements
prod(1:5)Try it ↗quantile(x, p)Quantiles (p from 0 to 1)
quantile(randn(1, 1000), 0.95)Try it ↗range(x) / range(A, dim)Largest minus smallest
range([4 9 2])Try it ↗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(x) / std(A, dim)Sample standard deviation
std(randn(1, 1000))Try it ↗sum(x) / sum(A, dim)Sum of elements (per column for matrices)
sum(1:100)Try it ↗tcdf(x, …)Student t cumulative probability, tcdf(t, dof)
tcdf(2.1, 15)Try it ↗tinv(x, …)Inverse of the t distribution, tinv(p, dof) — critical values
tinv(0.975, 15)Try it ↗tpdf(x, …)Student t density, tpdf(t, dof)
tpdf(0, 5)Try it ↗var(x) / var(A, dim)Sample variance
var(randn(1, 1000))Try it ↗zscore(x)Standardise: subtract the mean, divide by the standard deviation
zscore([2 4 6])Try it ↗conv(a, b)Convolution (also multiplies polynomials)
conv([1 1], [1 -1])Try it ↗cumtrapz(x, y)Running integral of sampled data
cumtrapz(0:0.5:2, [0 1 2 3 4])Try it ↗[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 ↗[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(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(y, h)Numerical derivative with central differences (same length as y)
x = 0:0.1:1; gradient(x.^2, x)Try it ↗integral(f, a, b)Definite integral of a function (adaptive Simpson rule)
integral(@(x) exp(-x.^2), -Inf, Inf)Try it ↗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(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 ↗[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 ↗[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 ↗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(p, x)Evaluate a polynomial (coefficients highest power first)
polyval([1 0 -1], 3)Try it ↗roots(p)All roots of a polynomial, including complex ones
roots([1 0 1])Try it ↗[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(x, y, xq)Natural cubic spline through the data points
spline(0:3, [0 1 0 1], 1.5)Try it ↗trapz(x, y) / trapz(y)Integral of sampled data (trapezoid rule)
x = linspace(0, pi); trapz(x, sin(x))Try it ↗and(a, b)Logical and (same as a & b)
and(1, 0)Try it ↗double(x)Convert to ordinary numbers (uint8 0–255 stays 0–255; use im2double for 0–1)
double('A')Try it ↗intersect(a, b)Values in both sets
intersect([1 2 3], [2 3 4])Try it ↗isequal(a, b)True if two values are identical
isequal([1 2], [1 2])Try it ↗[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(x)Convert to true/false (non-zero is true)
logical([2 0 -1])Try it ↗nnz(x)Number of non-zero elements
nnz([1 0 2 0])Try it ↗not(a)Logical not (same as ~a)
not([1 0])Try it ↗or(a, b)Logical or (same as a | b)
or(1, 0)Try it ↗setdiff(a, b)Values in a but not in b
setdiff(1:5, [2 4])Try it ↗union(a, b)Values in either set (sorted)
union([1 3], [2 3])Try it ↗[u, i, j] = unique(x)Sorted unique values (and where they come from)
unique([3 1 3 2 1])Try it ↗xor(a, b)Exclusive or
xor(true, false)Try it ↗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(s, pattern)True if the text contains the pattern
contains('MathLab', 'Lab')Try it ↗disp(x)Show a value without its name
disp('hello')Try it ↗endsWith(s, suffix)True if the text ends with the suffix
endsWith('data.csv', '.csv')Try it ↗fprintf('x = %g\n', x)Print formatted text to the command window
fprintf('%d squared is %d\n', 4, 16)Try it ↗int2str(x)Round and convert to text
int2str(2.7)Try it ↗lower(s)Lower case
lower('MathLab')Try it ↗mat2str(A)Matrix as text you can paste back
mat2str([1 2; 3 4])Try it ↗num2str(x) / num2str(x, digits)Number to text
['x = ' num2str(pi, 3)]Try it ↗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(s, pattern, replacement)Replace using a regular expression ($1 refers to groups)
regexprep('a1b22', '\d+', '#')Try it ↗sprintf('%.3f', x)Formatted text (%d %f %g %e %s, \n for a new line)
sprintf('%.2f and %d', pi, 7)Try it ↗startsWith(s, prefix)True if the text starts with the prefix
startsWith('MathLab', 'Math')Try it ↗str2num(s)Text to number
str2num('3.5') + 1Try it ↗strcat(a, b, …)Join text
strcat('ab', 'cd')Try it ↗strcmp(a, b)True if two texts are identical; with a cell array, one answer per cell
strcmp({'a', 'b'}, 'a')Try it ↗strcmpi(a, b)Like strcmp, ignoring upper/lower case
strcmpi('MathLab', 'mathlab')Try it ↗strjoin(c, delimiter)Join a cell array of text
strjoin({'a', 'b'}, '-')Try it ↗strrep(s, old, new)Replace text
strrep('a-b-c', '-', '+')Try it ↗parts = strsplit(s, delimiter)Split text into a cell array (default delimiter: whitespace)
strsplit('a,b,c', ',')Try it ↗strtrim(s)Remove leading and trailing spaces
strtrim(' hi ')Try it ↗upper(s)Upper case
upper('mathlab')Try it ↗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 ↗c = cell(n)An empty cell array with n elements
c = cell(3)Try it ↗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(s)Names of a struct's fields (cell array)
fieldnames(struct('a', 1, 'b', 2))Try it ↗getfield(s, 'name')Read a field by name
getfield(struct('a', 5), 'a')Try it ↗iscell(x)True for a cell array
iscell({1, 2})Try it ↗isfield(s, 'name')True if a struct has that field
isfield(struct('x', 1), 'x')Try it ↗isstruct(x)True for a struct
isstruct(5)Try it ↗num2cell(x)Put each number into its own cell
num2cell([1 2 3])Try it ↗rmfield(s, 'name')A copy of the struct without that field
rmfield(struct('a', 1, 'b', 2), 'a')Try it ↗setfield(s, 'name', v)A copy of the struct with a field set
s = setfield(struct(), 'a', 1)Try it ↗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 ↗angle(z)Phase angle in radians (atan2 of imaginary and real part)
angle(1i)Try it ↗complex(a, b)Build a + bi from real and imaginary parts
complex(1, 2)Try it ↗conj(z)Complex conjugate
conj(3 + 4i)Try it ↗imag(z)Imaginary part
imag(3 + 4i)Try it ↗isreal(x)True if x has no imaginary part
isreal(2i)Try it ↗real(z)Real part
real(3 + 4i)Try it ↗area(x, y)Filled area under a curve
x = 0:0.1:10; area(x, exp(-x/3).*sin(x).^2)Try it ↗bar(y) / bar(x, y, width)Bar chart
bar([3 7 2 5])Try it ↗barh(y) / barh(x, y)Horizontal bar chart
barh([40 25 20 15]); yticklabels({'Asia', 'Africa', 'Europe', 'Americas'})Try it ↗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(x, y, color)Filled polygon
t = linspace(0, 2*pi, 6); fill(cos(t), sin(t), 'r')Try it ↗fplot(f, [a b], 'style')Plot a function over an interval (default [-5 5])
fplot(@(x) sin(x)./x, [-20 20])Try it ↗histogram(data, nbins)Histogram of the values (default 20 bins)
histogram(randn(1, 2000), 40)Try it ↗loglog(x, y, …)Like plot, with a logarithmic x and y axis
x = logspace(0, 3); loglog(x, x.^2)Try it ↗pie(x) / pie(x, {'labels'})Pie chart of the shares of x
pie([45 30 15 10], {'Rent', 'Food', 'Travel', 'Other'})Try it ↗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(theta, r, 'style')Plot in polar coordinates (theta in radians)
th = linspace(0, 2*pi, 400); polarplot(th, cos(4*th))Try it ↗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(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(x, y, …)Like plot, with a logarithmic x axis
x = logspace(0, 3); semilogx(x, x.^2)Try it ↗semilogy(x, y, …)Like plot, with a logarithmic y axis
x = logspace(0, 3); semilogy(x, x.^2)Try it ↗stairs(x, y)Staircase plot: each value holds until the next sample
stairs(0:10, floor((0:10)/3))Try it ↗stem(x, y)Discrete samples as stems
n = 0:20; stem(n, 0.8.^n)Try it ↗text(x, y, 'label') / text(x, y, z, 'label')Put text at a data point
text(1, 0.5, 'peak')Try it ↗xline(x, 'style', 'label')Vertical reference line
xline(0, 'k--', 'threshold')Try it ↗yline(y, 'style', 'label')Horizontal reference line
yline(1, 'r:', 'limit')Try it ↗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(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(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(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(Z)Like imagesc, with a colorbar
heatmap(rand(8))Try it ↗imagesc(Z) / imagesc(x, y, Z)Show a matrix as a colour image (row 1 at the top)
imagesc(magic(9)); colorbarTry it ↗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 ↗Z = peaks(n) / peaks(X, Y)MATLAB's classic test surface
surf(peaks(40))Try it ↗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(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(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(x, y, z, 'style')Line in 3D
t = linspace(0, 10*pi, 800); plot3(sin(t), cos(t), t)Try it ↗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 flat / faceted / interpSurface edges: faceted shows the grid, flat and interp hide it
shading flatTry it ↗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(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 ↗axis equal / tight / auto / ij / xy / axis([xmin xmax ymin ymax])Axis limits and aspect
axis equalTry it ↗box on / box offFrame around the plot
box offTry it ↗cividis(n)The cividis colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(cividis)
colormap(cividis)Try it ↗Clear the figure
clfTry it ↗clim([lo hi])Fix the colour range
clim([-1 1])Try it ↗colorbar / colorbar offShow the colour scale
colorbarTry it ↗colormap name — viridis, plasma, magma, inferno, cividis, turbo, parula, coolwarm, rb, gray, hot, jet, oceanColour scheme for surfaces, images and contours. viridis, cividis and friends are perceptually uniform and print well.
colormap plasmaTry it ↗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(n)The gray colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(gray)
colormap(gray)Try it ↗grid on / grid offGrid lines
grid offTry it ↗hold on / hold offKeep existing plots when adding new ones
hold onTry it ↗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(n)The inferno colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(inferno)
colormap(inferno)Try it ↗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('a', 'b', …) / legend offLegend for the plotted lines (or use 'DisplayName' when plotting)
legend('sin', 'cos')Try it ↗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(n)The ocean colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(ocean)
colormap(ocean)Try it ↗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(n)The plasma colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(plasma)
colormap(plasma)Try it ↗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(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('text')Smaller line under the title
subtitle('γ = 0.2')Try it ↗title('text')Axes title
title('Damped oscillation')Try it ↗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(n)The viridis colormap as an n×3 matrix of RGB rows (default 256); use it with colormap(viridis)
colormap(viridis)Try it ↗xlabel('text')x-axis label
xlabel('time (s)')Try it ↗xlim([a b])x-axis limits
xlim([0 10])Try it ↗xticklabels({'a', 'b', …})Text for the x-axis ticks
bar([3 5 2]); xticklabels({'low', 'mid', 'high'})Try it ↗xticks([positions])Where the x-axis ticks go
plot(0:10); xticks(0:2:10)Try it ↗ylabel('text')y-axis label
ylabel('amplitude')Try it ↗ylim([a b])y-axis limits
ylim([-1 1])Try it ↗yticklabels({'a', 'b', …})Text for the y-axis ticks
barh([3 5 2]); yticklabels({'A', 'B', 'C'})Try it ↗yticks([positions])Where the y-axis ticks go
plot(0:10); yticks([0 5 10])Try it ↗zlabel('text')z-axis label
zlabel('height')Try it ↗zlim([a b])z-axis limits
zlim([0 2])Try it ↗close allAccepted for compatibility (clears the figure)
close allTry it ↗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(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('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('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(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 ↗ax = gcaThe current axes (for set)
set(gca, 'FontSize', 14)Try it ↗f = gcfThe current figure (for set, exportgraphics)
exportgraphics(gcf, 'figure.png', 'Resolution', 300)Try it ↗opengl hardware / opengl software / opengl infoChoose 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('-dpng', '-r300', 'name')Save the figure, MATLAB print style (-dpng, -dsvg, -dpdf, -r<dpi>)
print('-dpdf', '-r600', 'figure')Try it ↗saveas(gcf, 'name.png')Save the figure (PNG, SVG or PDF)
saveas(gcf, 'figure.svg')Try it ↗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 name — default, web, paper, ieee, ieee-wide, nature, thesis, slides, poster, minimal, grayscale, dark, lightApply 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 ↗List the figure style presets
stylesTry it ↗theme light / theme dark / theme autoBackground of the figure (as in MATLAB): light, dark, or follow the page
theme darkTry it ↗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 ↗Accepted for compatibility (MathLab draws when the script ends)
drawnowTry it ↗pause(s)Not supported inside a script — use animate(seconds) and the time variable t instead
animate(5)Try it ↗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(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(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 ↗blackman(n)Blackman window (column vector) — very low side lobes
blackman(8)'Try it ↗C = conv2(A, B, 'full' | 'same' | 'valid')2-D convolution
conv2([1 2; 3 4], [1 1; 1 1])Try it ↗downsample(x, k)Keep every k-th sample
downsample(1:10, 3)Try it ↗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(X)Move the zero frequency to the middle of the spectrum
fftshift(1:6)Try it ↗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 ↗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 ↗[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(n)Hamming window (column vector)
hamming(8)'Try it ↗hann(n)Hann window (column vector) — reduces spectral leakage
hann(8)'Try it ↗ifft(X) / ifft(X, n)Inverse Fourier transform
real(ifft(fft([1 2 3])))Try it ↗ifftshift(X)Undo fftshift
ifftshift(fftshift(1:5))Try it ↗unwrap(phase)Remove 2π jumps from a phase signal
unwrap([0 3 -3])Try it ↗upsample(x, k)Insert k−1 zeros between samples
upsample([1 2 3], 2)Try it ↗[r, lags] = xcorr(x, y)Cross-correlation (autocorrelation with one input)
[r, lags] = xcorr([1 2 3 2 1]);Try it ↗BW2 = bwareaopen(BW, P)Remove regions smaller than P pixels
BW2 = bwareaopen(imbinarize(testimage('blobs')), 200);Try it ↗[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 ↗P = bwperim(BW)Outline pixels of the white regions
P = bwperim(imbinarize(testimage('blobs')));Try it ↗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 ↗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 ↗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 ↗level = graythresh(I)Otsu's threshold (0–1) that best separates dark and bright pixels
graythresh(testimage('blobs'))Try it ↗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 ↗RGB = hsv2rgb(HSV)Colour image from hue, saturation and value
hsv2rgb(cat(3, 0.6, 1, 1))Try it ↗im2double(I)Image as doubles from 0 to 1 (uint8 is divided by 255)
im2double(uint8([0 128 255]))Try it ↗G = im2gray(I)Grey version of an image (unchanged if it is already grey)
G = im2gray(testimage('shapes'));Try it ↗im2uint8(I)Image as uint8 0–255 (doubles from 0–1 are scaled)
im2uint8([0 0.5 1])Try it ↗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 ↗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 ↗BW2 = imclearborder(BW)Remove the white regions that touch the edge of the image
BW2 = imclearborder(imbinarize(testimage('blobs')));Try it ↗J = imclose(I, se)Closing (dilate, then erode): fills small dark gaps
J = imclose(imbinarize(testimage('blobs')), strel('disk', 5));Try it ↗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 ↗J = imdilate(I, se)Dilation: the maximum of the neighbourhood (grows bright regions)
J = imdilate(imbinarize(testimage('blobs')), strel('disk', 3));Try it ↗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 ↗BW2 = imfill(BW, 'holes')Fill holes: dark areas completely surrounded by white
BW2 = imfill(edge(rgb2gray(testimage('shapes')), 'canny'), 'holes');Try it ↗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 ↗info = imfinfo('photo.jpg')Size of an imported image (Width, Height, original size if it was scaled down)
info = imfinfo('photo.jpg')Try it ↗J = imgaussfilt(I, sigma)Gaussian blur (sigma in pixels, default 0.5)
J = imgaussfilt(testimage('shapes'), 4);Try it ↗[Gmag, Gdir] = imgradient(I, 'sobel' | 'prewitt')Gradient magnitude and direction (degrees, −180 to 180)
imshow(imgradient(rgb2gray(testimage('shapes'))), [])Try it ↗[Gx, Gy] = imgradientxy(I, 'sobel' | 'prewitt')Horizontal and vertical brightness gradients
[Gx, Gy] = imgradientxy(rgb2gray(testimage('shapes')));Try it ↗[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 ↗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 ↗J = imopen(I, se)Opening (erode, then dilate): removes small bright specks
J = imopen(imbinarize(testimage('blobs')), strel('disk', 5));Try it ↗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 ↗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 ↗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 ↗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 ↗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(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(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 ↗T = imtile({I1, I2, …})One image with the given images in a grid
T = imtile({testimage('shapes'), testimage('texture')});Try it ↗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 ↗RGB = label2rgb(L)Colour each labelled region (from bwlabel) differently; label 0 is white
label2rgb(bwlabel(testimage('blobs') > 0.5))Try it ↗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({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 ↗P = phantom(n)The Shepp–Logan head phantom (modified), the standard test image of medical imaging and tomography
imshow(phantom(256))Try it ↗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 ↗G = rgb2gray(RGB)Grey image from a colour image (0.299 R + 0.587 G + 0.114 B)
G = rgb2gray(testimage('shapes'));Try it ↗HSV = rgb2hsv(RGB)Hue, saturation and value (each 0–1) of a colour image
hsv = rgb2hsv(testimage('shapes'));Try it ↗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 ↗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 ↗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(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 ↗[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 ↗txt = fileread('notes.txt')The whole file (or web page) as text
txt = fileread('notes.txt')Try it ↗List the imported files
filesTry it ↗height(T)Number of rows of a table (or matrix)
height(T)Try it ↗isfile('data.csv')True if that file has been imported
isfile('data.csv')Try it ↗v = jsondecode(text)JSON text → MathLab values (objects become structs, lists become arrays or cells)
s = jsondecode('{"a": [1, 2, 3]}')Try it ↗txt = jsonencode(v)MathLab value → JSON text
jsonencode(struct('x', [1 2 3]))Try it ↗A = load('data.txt')Load numbers from an uploaded text/CSV file
A = load('data.txt')Try it ↗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 ↗lines = readlines('notes.txt')The lines of a text file (cell array)
lines = readlines('notes.txt')Try it ↗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 ↗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 ↗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(T)Number of columns of a table (or matrix)
width(T)Try it ↗writematrix(A, 'out.csv')Save a matrix as a CSV file (offered as a download)
writematrix(magic(4), 'magic.csv')Try it ↗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 ↗[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 ↗[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 ↗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 ↗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 ↗[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 ↗[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 ↗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 ↗[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 ↗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 ↗e = effrr(rate, m)Effective annual rate of a nominal rate compounded m times a year
effrr(0.05, 12)Try it ↗[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 ↗fv = fvfix(rate, nper, pmt)Future value of a fixed payment saved each period
fvfix(0.05/12, 360, 200)Try it ↗fv = fvvar(cashflows, rate)Future value (at the last period) of a series of cash flows
fvvar([-100 -100 -100], 0.05)Try it ↗r = irr(cashflows)Internal rate of return: the rate where the NPV is zero
irr([-1000 300 400 500])Try it ↗[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 ↗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(x, k)Moving maximum
movmax([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗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(x, k)Moving minimum
movmin([4 8 6 -1 -2 -3 -1 3 4 5], 3)Try it ↗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(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 ↗r = nomrr(e, m)Nominal rate compounded m times a year that gives effective annual rate e
nomrr(0.0512, 12)Try it ↗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 ↗[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 ↗pv = pvfix(rate, nper, pmt)Present value of a fixed payment received each period
pvfix(0.05, 20, 1000)Try it ↗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 ↗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 ↗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 ↗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 ↗[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 ↗[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 ↗[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 ↗[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 ↗[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 ↗[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 ↗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 ↗[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 ↗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 ↗k = dcgain(G)Gain at zero frequency (the final value of the step response, if stable)
dcgain(tf(3, [1 2]))Try it ↗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(G) / [y, t] = impulse(G)Response to a unit impulse
impulse(tf(1, [1 0.6 1]))Try it ↗isstable(G)True if every pole has a negative real part
isstable(tf(1, [1 -1]))Try it ↗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 ↗[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 ↗G = minreal(G)Cancel matching poles and zeros
minreal(tf([1 1], [1 3 2]))Try it ↗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 ↗G = parallel(G1, G2)Two systems side by side, outputs added
parallel(tf(1, [1 1]), tf(2, [1 3]))Try it ↗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 ↗[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 ↗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 ↗p = pole(G)Poles (roots of the denominator)
pole(tf(1, [1 2 5]))Try it ↗pzmap(G)Poles (×) and zeros (○) in the complex plane
pzmap(tf([1 2], [1 2 5]))Try it ↗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 ↗G = series(G1, G2)Two systems one after the other (G2 G1)
series(tf(1, [1 1]), tf(2, [1 3]))Try it ↗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 ↗S = stepinfo(G)Step response numbers: RiseTime (10–90 %), SettlingTime (2 %), Overshoot (%), Peak, PeakTime
S = stepinfo(tf(1, [1 0.6 1]))Try it ↗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 ↗[num, den] = tfdata(G)Coefficients of the numerator and denominator
[n, d] = tfdata(tf(1, [1 2]))Try it ↗z = zero(G)Zeros (roots of the numerator)
zero(tf([1 3], [1 2 5]))Try it ↗G = zpk(zeros, poles, gain)Transfer function from zeros, poles (complex values allowed) and a gain
G = zpk([], [-1 -2], 4)Try it ↗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(expr, x)Group terms by powers of x
syms x a; collect(a*x + x^2 + 2*a*x, x)Try it ↗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(expr)Multiply out products and powers
syms x; expand((x + 1)^3)Try it ↗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(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(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 ↗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(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(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 ↗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 ↗[n, d] = numden(expr)Numerator and denominator
syms x; [n, d] = numden((x + 1)/(x^2 - 1))Try it ↗pretty(expr)Print an expression
syms x; pretty((x + 1)/(x - 1))Try it ↗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 ↗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(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 ↗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 x y zCreate symbolic variables (assumptions such as real or positive are accepted and ignored)
syms x yTry it ↗symvar(expr)The symbolic variables in an expression
syms x y; symvar(x*y + 1)Try it ↗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(expr, digits)Evaluate to a decimal number (shown with the given number of digits)
vpa(sym(pi), 10)Try it ↗[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 ↗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 ↗[acf, lags] = autocorr(y, numLags)Sample autocorrelation (plotted with 95 % bounds when no output is asked for)
autocorr(randn(200, 1))Try it ↗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 ↗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 ↗[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 ↗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 ↗E = infer(EstMdl, y)Residuals of an estimated ARIMA model, or conditional variances of a GARCH model
v = infer(EstMdl, r)Try it ↗[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 ↗[pacf, lags] = parcorr(y, numLags)Sample partial autocorrelation — the lag where it cuts off suggests the AR order
parcorr(randn(200, 1))Try it ↗[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 ↗[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 ↗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 ↗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(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 ↗km = deg2km(deg)Degrees of arc on the Earth to kilometres (radius 6371 km)
deg2km(1)Try it ↗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(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(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(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(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 ↗assert(condition, 'message')Stop with an error if the condition is false
assert(1 + 1 == 2)Try it ↗class(x)The type of a value
class(pi)Try it ↗Clear the command window
clcTry it ↗clear / clear x yRemove variables from the workspace
clear xTry it ↗[a, b] = deal(x, y)Copy inputs to outputs (one input → all outputs)
[a, b] = deal(1, 2)Try it ↗error('message')Stop with an error message
error('Something went wrong')Try it ↗feval(f, args…)Call a function value
feval(@sin, pi/2)Try it ↗format long / format shortShow more or fewer digits
format long; piTry it ↗help / help nameList the functions, or explain one
help plotTry it ↗isa(x, 'double')Check the type of a value
isa(pi, 'double')Try it ↗ischar(x)True for text
ischar('a')Try it ↗isnumeric(x)True for numbers and matrices
isnumeric(3)Try it ↗Start a stopwatch
tic; sum(1:1e6); tocTry it ↗Seconds since tic
tic; tocTry it ↗warning('message')Show a warning and carry on
warning('Careful')Try it ↗List the variables in the workspace
whoTry it ↗Variables with their size and type
whosTry it ↗No function matches.