Polyglot
Languages MATLAB stdlib
MATLAB § stdlib

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:

FamilyFunctions
Trigonometrysin, cos, tan, asin, acos, atan, atan2, sind, cosd, tand (degree versions)
Hyperbolicsinh, cosh, tanh, asinh, acosh, atanh
Exponential / logexp, log, log2, log10, expm1, log1p
Powers / rootssqrt, cbrt, nthroot, hypot
Roundinground, floor, ceil, fix, mod, rem, sign
Specialgamma, gammaln, factorial, beta, erf, erfc, besselj, bessely, airy
Complexreal, 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

FunctionReturns
sum, prodSum / product along a dimension
mean, median, modeCentral tendency
min, maxExtreme values (and their indices)
std, varStandard deviation, variance
cumsum, cumprod, cummax, cumminCumulative
diffFirst-order difference
any, allLogical reductions
nnzCount of non-zero entries
uniqueUnique values, sorted
histcounts, histogramHistogram
corrcoef, covCorrelation, covariance
quantile, prctileQuantiles

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

FamilyFunctionsNotes
Root-findingfzero, rootsScalar root and polynomial roots
Optimisation (unconstrained scalar)fminbnd, fminsearchDerivative-free
Numerical integrationintegral, integral2, integral3, trapz, quad2dAdaptive and trapezoidal
ODEsode45, ode23, ode113, ode15s, ode23sRunge-Kutta and stiff solvers
Interpolationinterp1, interp2, interp3, interpn, griddedInterpolant, scatteredInterpolant1-d through N-d
FFTfft, ifft, fft2, fftn, fftshiftFast Fourier transforms
Polynomialspolyval, polyfit, roots, poly, conv, deconvEvaluation, fitting, roots
Curve fittingpolyfit, lsqnonlin, lsqcurvefitThe 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:

FunctionReads / writes
readtable, writetableTables from/to CSV, Excel, text
readmatrix, writematrixNumeric matrices from/to text
readmatrix, csvreadNumeric CSV (older API)
load, saveMAT-files (the native MATLAB binary format)
fopen, fclose, fread, fwrite, fprintf, fscanfLow-level file I/O (C-style)
readtimetable, writetimetableTime-series tables
parquetread, parquetwriteApache Parquet
h5read, h5write, h5createHDF5
ncread, ncwriteNetCDF
xmlread, xmlwrite, readstruct, writestructXML / JSON / structured formats
imread, imwriteImages (most formats)
audioread, audiowriteAudio (WAV, MP3, FLAC)
videoReader, videoWriterVideo

File I/O is covered at greater length in File I/O and MEX.

Strings and regular expressions

FunctionAction
sprintf, composeBuild a string (returns char / string)
fprintfPrint to file or console
disp, displayDisplay a value
strcmp, strcmpi, strncmpString comparison
strfindFirst index of substring
strrep, replaceSubstring replacement
strsplit, split, joinTokenise and join
regexp, regexprep, regexpiRegular expressions
upper, lower, strtrim, strip, padCase and trimming
contains, startsWith, endsWithPredicates 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

ClassConstruction
datetimedatetime('today'), datetime(2024, 1, 15)
durationhours(5), minutes(30), seconds(1.5)
calendarDurationcalmonths(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:

FunctionPlots
plot(x, y)Line plot
scatter(x, y)Scatter
bar(x, y), barhBar 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), contourfContours
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.