Standard library
MATLAB’s standard library is, by the standards of general-purpose languages, enormous. The base product ships with several thousand functions covering numerical linear algebra, signal processing, statistics, numerical integration, optimisation, graphics, and file I/O; the toolboxes add many thousands more in specialised domains. This page is a guided tour of the base library — the functions a working MATLAB programmer reaches for without needing to install anything additional. Toolbox-specific functions are noted where they fill an important gap.
Elementary math
The element-wise math functions accept arrays and return arrays of the same shape:
| Family | Functions |
|---|---|
| Trigonometry | sin, cos, tan, asin, acos, atan, atan2, sind, cosd, tand (degree versions) |
| Hyperbolic | sinh, cosh, tanh, asinh, acosh, atanh |
| Exponential / log | exp, log, log2, log10, expm1, log1p |
| Powers / roots | sqrt, cbrt, nthroot, hypot |
| Rounding | round, floor, ceil, fix, mod, rem, sign |
| Special | gamma, gammaln, factorial, beta, erf, erfc, besselj, bessely, airy |
| Complex | real, imag, conj, abs, angle |
The sind/cosd/tand family takes degrees rather than radians — a small but practical convenience for engineering work.
Linear algebra
The base library exposes most of LAPACK and ARPACK through high-level functions:
A = rand(5);
b = rand(5, 1);
x = A \ b; % solve A*x = b
[L, U, P] = lu(A); % LU with pivoting
[Q, R] = qr(A); % QR
[U, S, V] = svd(A); % SVD
[V, D] = eig(A); % eigendecomposition
R = chol(A' * A); % Cholesky (requires positive definite)
inv(A) % inverse — rarely the right choice; A\eye is similar
pinv(A) % Moore-Penrose pseudo-inverse
det(A) % determinant
trace(A) % trace
rank(A) % numerical rank
cond(A) % condition number
norm(A) % 2-norm (largest singular value)
null(A) % null-space basis
orth(A) % column-space basis
The matrix-function family — expm, logm, sqrtm, funm — computes matrix functions (not element-wise). The convention is that f(A) is element-wise; fm(A) (with the trailing m) is the matrix function. The pair sqrt(A) and sqrtm(A) are the most-cited example of the distinction.
Reduction and statistics
| Function | Returns |
|---|---|
sum, prod | Sum / product along a dimension |
mean, median, mode | Central tendency |
min, max | Extreme values (and their indices) |
std, var | Standard deviation, variance |
cumsum, cumprod, cummax, cummin | Cumulative |
diff | First-order difference |
any, all | Logical reductions |
nnz | Count of non-zero entries |
unique | Unique values, sorted |
histcounts, histogram | Histogram |
corrcoef, cov | Correlation, covariance |
quantile, prctile | Quantiles |
Most reductions accept a dim argument to specify the dimension along which to reduce; without it, they collapse along the first non-singleton dimension. The 'all' keyword reduces over every dimension to a scalar. The 'omitnan' option skips NaN values.
A = magic(4);
sum(A) % 1×4: column sums
sum(A, 2) % 4×1: row sums
sum(A, 'all') % scalar: total
mean(A, 'omitnan') % skip NaN
Sorting and searching
sort(x) % ascending
sort(x, 'descend') % descending
[sorted, idx] = sort(x); % with permutation
sortrows(A) % lexicographic on rows
unique(x) % unique values
find(x > 5) % indices of non-zero entries
ismember(x, [1 2 3]) % membership test
intersect(a, b) % set intersection
union(a, b) % set union
setdiff(a, b) % set difference
The find function is essential MATLAB idiom: applied to a logical array, it returns the linear indices of the true entries.
Random numbers
rand(3, 3) % uniform [0, 1)
randn(3, 3) % standard normal
randi(10, 3, 3) % integer in 1..10
randperm(10) % random permutation of 1..10
randsample(1:100, 10) % sample without replacement
rng(42) % seed the generator
s = rng; % save state
rng(s) % restore
The Statistics Toolbox extends the library with random('Normal', mu, sigma, m, n) and many specific distributions; the base library covers uniform, normal, and integer sampling.
Numerical algorithms
| Family | Functions | Notes |
|---|---|---|
| Root-finding | fzero, roots | Scalar root and polynomial roots |
| Optimisation (unconstrained scalar) | fminbnd, fminsearch | Derivative-free |
| Numerical integration | integral, integral2, integral3, trapz, quad2d | Adaptive and trapezoidal |
| ODEs | ode45, ode23, ode113, ode15s, ode23s | Runge-Kutta and stiff solvers |
| Interpolation | interp1, interp2, interp3, interpn, griddedInterpolant, scatteredInterpolant | 1-d through N-d |
| FFT | fft, ifft, fft2, fftn, fftshift | Fast Fourier transforms |
| Polynomials | polyval, polyfit, roots, poly, conv, deconv | Evaluation, fitting, roots |
| Curve fitting | polyfit, lsqnonlin, lsqcurvefit | The latter two require Optimization Toolbox |
% Quick example: solve y' = -2y, y(0) = 1
[t, y] = ode45(@(t, y) -2*y, [0 5], 1);
plot(t, y)
File I/O
The principal entry points:
| Function | Reads / writes |
|---|---|
readtable, writetable | Tables from/to CSV, Excel, text |
readmatrix, writematrix | Numeric matrices from/to text |
readmatrix, csvread | Numeric CSV (older API) |
load, save | MAT-files (the native MATLAB binary format) |
fopen, fclose, fread, fwrite, fprintf, fscanf | Low-level file I/O (C-style) |
readtimetable, writetimetable | Time-series tables |
parquetread, parquetwrite | Apache Parquet |
h5read, h5write, h5create | HDF5 |
ncread, ncwrite | NetCDF |
xmlread, xmlwrite, readstruct, writestruct | XML / JSON / structured formats |
imread, imwrite | Images (most formats) |
audioread, audiowrite | Audio (WAV, MP3, FLAC) |
videoReader, videoWriter | Video |
File I/O is covered at greater length in File I/O and MEX.
Strings and regular expressions
| Function | Action |
|---|---|
sprintf, compose | Build a string (returns char / string) |
fprintf | Print to file or console |
disp, display | Display a value |
strcmp, strcmpi, strncmp | String comparison |
strfind | First index of substring |
strrep, replace | Substring replacement |
strsplit, split, join | Tokenise and join |
regexp, regexprep, regexpi | Regular expressions |
upper, lower, strtrim, strip, pad | Case and trimming |
contains, startsWith, endsWith | Predicates on strings |
The string class methods (covered in Strings and char arrays) overlap with these and are usually the cleaner choice in new code.
Date and time
| Class | Construction |
|---|---|
datetime | datetime('today'), datetime(2024, 1, 15) |
duration | hours(5), minutes(30), seconds(1.5) |
calendarDuration | calmonths(3), calyears(1) |
now = datetime("now");
yesterday = now - days(1);
weeksAhead = now + calweeks(4);
elapsed = duration(0, 30, 0); % 30 minutes
The classes integrate with table and timetable; the older datenum / datevec functions remain available but are discouraged in new code.
Graphics
The 2-d plotting workhorses:
| Function | Plots |
|---|---|
plot(x, y) | Line plot |
scatter(x, y) | Scatter |
bar(x, y), barh | Bar chart |
histogram(x) | Histogram |
boxplot(x) | Box plot |
errorbar(x, y, err) | Error bars |
stairs(x, y), stem(x, y) | Step / stem |
imagesc(A), imshow(A) | Image / matrix display |
contour(X, Y, Z), contourf | Contours |
quiver(X, Y, U, V) | Vector field |
For 3-d: plot3, surf, mesh, surfc, scatter3, streamline. The figure, axes, title, xlabel, ylabel, legend, colorbar, xlim, ylim, grid, hold family configures the surrounding plot. Modern code uses tiledlayout and nexttile (R2019b+) to compose multi-panel figures; older code used subplot.
figure
tiledlayout(2, 2)
nexttile; plot(1:10); title("Linear")
nexttile; semilogy(1:10); title("Log y")
nexttile; histogram(randn(1000, 1)); title("Histogram")
nexttile; imagesc(magic(10)); title("Imagesc")
Where the standard library ends
The base library covers an enormous surface; the toolboxes extend it further. The most-commonly-installed toolboxes are:
- Statistics and Machine Learning — distributions, hypothesis tests, classification, regression, clustering, machine-learning algorithms.
- Signal Processing — filter design, spectral estimation, filter banks.
- Image Processing — morphology, registration, segmentation, region properties.
- Control System — LTI models, root locus, PID tuning.
- Optimization and Global Optimization — linear, quadratic, nonlinear, integer programming, and global solvers.
- Symbolic Math — computer-algebra system.
- Curve Fitting — interactive curve and surface fitting.
- Deep Learning — training and inference of neural networks.
Each toolbox is a separately licensed addition; check ver to see which are installed on the current MATLAB. The official function reference at mathworks.com/help/matlab is the authoritative index and is the right place to look up details on individual functions.