Matrix Functions (50)

Matrix operations, decompositions, linear algebra

characteristicPolynomial
Compute the characteristic polynomial det(lambda*I - A) of a square matrix using the Faddeev-LeVerrier algorithm. Returns an array of coefficients in ascending order [c_0, c_1, ..., c_n] where c_0 + c_1*lambda + ... + c_n*lambda^n.
Syntax
characteristicPolynomial(A)
Parameters
NameTypeDescription
AArray | MatrixA square matrix
Returns
number[] — Polynomial coefficients [c_0, c_1, ..., c_n]
Examples
characteristicPolynomial([[2
0
See Also
eigs det trace
cholesky
Compute the Cholesky decomposition of a symmetric positive definite matrix A. Returns a lower triangular matrix L such that A = L * L^T.
Syntax
cholesky(A)
Parameters
NameTypeDescription
AArray | MatrixA symmetric positive definite matrix
Returns
Array | Matrix — Lower triangular matrix L
Examples
cholesky([[4
2
See Also
qr lup svd eigs
column
Return a column from a matrix or array.
Syntax
column(x | index)
Type Signatures
Array, number
Parameters
NameTypeDescription
valueArray | Matrix An array or matrix
columnnumberThe index of the column
Returns
Array | Matrix — The retrieved column
Examples
A = [[1
2
concat
Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.
Syntax
concat(A | B | C
Type Signatures
...Array | Matrix | number | BigNumber, ...string
Parameters
NameTypeDescription
args... Array | MatrixTwo or more matrices
Returns
Array | Matrix — Concatenated matrix
Examples
A = [1
2; 5
6
count
Count the number of elements of a matrix, array or string.
Syntax
count(x)
Type Signatures
Matrix | Array
Parameters
NameTypeDescription
xstring | Array | MatrixA matrix or string
Returns
number — An integer with the elements in `x`.
Examples
a = [1
2; 3
4; 5
6
See Also
size
cross
Calculate the cross product for two vectors in three dimensional space.
Syntax
cross(A | B)
Type Signatures
Matrix, Matrix, Matrix, Array, Array, Matrix
Parameters
NameTypeDescription
xArray | MatrixFirst vector
yArray | MatrixSecond vector
Returns
Array | Matrix — Returns the cross product of `x` and `y`
Examples
cross([1
1
0
See Also
multiply dot
ctranspose
Complex Conjugate and Transpose a matrix
Syntax
x\ | ctranspose(x)
Parameters
NameTypeDescription
xArray | MatrixMatrix to be ctransposed
Returns
Array | Matrix — The ctransposed matrix
Examples
a = [1
2
3; 4
5
6
det
Calculate the determinant of a matrix
Syntax
det(x)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
xArray | MatrixA matrix
Returns
number — The determinant of `x`
Examples
det([1
2; 3
4
diag
Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved,
Syntax
diag(x) | diag(x | k)
Type Signatures
Array, number, Array, BigNumber, Array, string, Array, number, string, Array, BigNumber, string, Matrix, number
Parameters
NameTypeDescription
xMatrix | ArrayA two dimensional matrix or a vector
Returns
Matrix | Array — Diagonal matrix from input vector, or diagonal from input matrix.
Examples
diag(1:3)
diag(1:3
1)
a = [1
2
diff
Syntax
diff(arr) | diff(arr | dim)
Type Signatures
Array | Matrix, Array | Matrix, number
Parameters
NameTypeDescription
arrArray | MatrixAn array or matrix
dimnumber | BigNumberDimension
Returns
Array | Matrix — Difference between array elements in given dimension
Examples
A = [1
2
4
7
0
dot
Calculate the dot product of two vectors.
Syntax
dot(A | B) | A * B
Parameters
NameTypeDescription
xArray | MatrixFirst vector
yArray | MatrixSecond vector
Returns
number — Returns the dot product of `x` and `y`
Examples
dot([2
4
1
See Also
multiply cross
eigs
Calculate the eigenvalues and optionally eigenvectors of a square matrix
Syntax
eigs(x)
Type Signatures
Array, number|BigNumber, Matrix, number|BigNumber, Matrix, Object
Parameters
NameTypeDescription
xArray | MatrixMatrix to be diagonalized
optsnumber | BigNumber | OptsObjectObject with keys `precision`, defaulting to config.relTol, and `eigenvectors`, defaulting to true and specifying whether to compute eigenvectors. If just a number, specifies precision.
Returns
{values: Array|Matrix, eigenvectors?: Array<EVobj> — } Object containing an array of eigenvalues and an array of {value: number|BigNumber, vector: Array|Matrix} objects. The eigenvectors property is undefined if eigenvectors were not requested.
Examples
eigs([[5
2.3
See Also
inv
fft
Calculate N-dimensional Fourier transform
Syntax
fft(x)
Parameters
NameTypeDescription
arrArray | MatrixAn array or matrix
Returns
Array | Matrix — N-dimensional Fourier transformation of the array
Examples
fft([[1
0
See Also
ifft
filter
Filter items in a matrix.
Syntax
filter(x | test)
Type Signatures
Matrix, function, Matrix, RegExp
Parameters
NameTypeDescription
xMatrix | ArrayA one dimensional matrix or array to filter
testFunction | RegExp
Returns
Matrix | Array — Returns the filtered matrix.
Examples
isPositive(x) = x > 0
filter([6
-2
-1
4
See Also
sort map forEach
flatten
Flatten a multi dimensional matrix into a single dimensional matrix.
Syntax
flatten(x)
Parameters
NameTypeDescription
xDenseMatrix | ArrayMatrix to be flattened
Returns
DenseMatrix | Array — Returns the flattened matrix
Examples
a = [1
2
3; 4
5
6
forEach
Iterates over all elements of a matrix/array, and executes the given callback function.
Syntax
forEach(x | callback)
Type Signatures
Matrix, function
Parameters
NameTypeDescription
xMatrix | ArrayThe matrix to iterate on.
callbackFunctionThe callback function is invoked with three
Examples
numberOfPets = {}
addPet(n) = numberOfPets[n
See Also
map sort filter
getMatrixDataType
Find the data type of all elements in a matrix or array,
Syntax
getMatrixDataType(x)
Parameters
NameTypeDescription
x...Matrix | ArrayThe Matrix with values.
Returns
string — A string representation of the matrix type
Examples
getMatrixDataType([1
2
3
See Also
matrix sparse typeOf
hessenbergForm
Reduce a square matrix A to upper Hessenberg form using Householder reflections. Returns an object { H, Q } where H is upper Hessenberg (zeros below the first subdiagonal) and Q is orthogonal, satisfying A = Q * H * Q^T.
Syntax
hessenbergForm(A)
Parameters
NameTypeDescription
AArray | MatrixA square matrix
Returns
{ H: Array|Matrix, Q: Array|Matrix — }
Examples
hessenbergForm([[4
1
2
See Also
qr schur eigs svd
identity
Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.
Syntax
identity(n) | identity(m | n)
Type Signatures
number | BigNumber, number | BigNumber, string, number | BigNumber, number | BigNumber, number | BigNumber, number | BigNumber, string, Array, string, Matrix, string
Parameters
NameTypeDescription
size...number | Matrix | ArrayThe size for the matrix
formatstringThe Matrix storage format
Returns
Matrix | Array | number — A matrix with ones on the diagonal.
Examples
identity(3)
identity(3
5)
a = [1
2
ifft
Calculate N-dimensional inverse Fourier transform
Syntax
ifft(x)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
arrArray | MatrixAn array or matrix
Returns
Array | Matrix — N-dimensional Fourier transformation of the array
Examples
ifft([[2
2
See Also
fft
inv
Calculate the inverse of a matrix
Syntax
inv(x)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
xnumber | Complex | Array | MatrixMatrix to be inversed
Returns
number | Complex | Array | Matrix — The inverse of `x`.
Examples
inv([1
2; 3
4
jordanForm
Compute the Jordan normal form J of a square matrix A and a transition matrix P such that A = P * J * inv(P). For simple eigenvalues the result is diagonal; for repeated eigenvalues Jordan blocks with 1s on the superdiagonal are constructed.
Syntax
jordanForm(A)
Parameters
NameTypeDescription
AArray | MatrixA square matrix
Returns
{ J: Array|Matrix, P: Array|Matrix — }
Examples
jordanForm([[2
0
See Also
eigs schur svd
kron
Calculates the Kronecker product of 2 matrices or vectors.
Syntax
kron(x | y)
Type Signatures
Matrix, Matrix, Matrix, Array, Array, Matrix
Parameters
NameTypeDescription
xArray | MatrixFirst vector
yArray | MatrixSecond vector
Returns
Array | Matrix — Returns the Kronecker product of `x` and `y`
Examples
kron([[1
0
See Also
multiply dot cross
map
Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array or the matrices/arrays.
Syntax
map(x | callback) | map(x
Type Signatures
Matrix, function
Parameters
NameTypeDescription
xMatrix | ArrayThe input to iterate on.
callbackFunction
Returns
Matrix | array —
Examples
map([1
2
3
See Also
filter forEach
mapSlices
Generate a matrix one dimension less than A by applying callback to
Syntax
mapSlices(A | dim | callback)
Type Signatures
Array | Matrix, number | BigNumber, function
Parameters
NameTypeDescription
arrayArray | MatrixThe input Matrix
dimnumberThe dimension along which the callback is applied
callbackFunctionThe callback function that is applied. This Function
Returns
Array | Matrix — res The residual matrix with the function mapped on the slices over some dimension.
Examples
A = [[1
2
See Also
map forEach
matrixFromColumns
Create a dense matrix from vectors as individual columns.
Syntax
matrixFromColumns(...arr) | matrixFromColumns(row1 | row2)
Type Signatures
...
Parameters
NameTypeDescription
cols... Array | MatrixMultiple columns
Returns
number[][] | Matrix — if at least one of the arguments is an array, an array will be returned
Examples
matrixFromColumns([1
2
3
matrixFromFunction
Create a matrix by evaluating a generating function at each index.
Syntax
matrixFromFunction(size | fn) | matrixFromFunction(size
Type Signatures
Array | Matrix, function, string, string, Array | Matrix, function, string, Matrix, function, Array, function, Array | Matrix, string, function, Array | Matrix, string, string, function
Parameters
NameTypeDescription
sizeArray | MatrixThe size of the matrix to be created
fnfunctionCallback function invoked for every entry in the matrix
formatstringThe Matrix storage format, either `'dense'` or `'sparse'`
datatypestringType of the values
Returns
Array | Matrix — Returns the created matrix
Examples
f(I) = I[1
matrixFromRows
Create a dense matrix from vectors as individual rows.
Syntax
matrixFromRows(...arr) | matrixFromRows(row1 | row2)
Type Signatures
...
Parameters
NameTypeDescription
rows... Array | MatrixMultiple rows
Returns
number[][] | Matrix — if at least one of the arguments is an array, an array will be returned
Examples
matrixFromRows([1
2
3
matrixLog
Compute the principal matrix logarithm of a square matrix A using eigendecomposition. Returns L such that expm(L) ≈ A. Requires that A has strictly positive real eigenvalues.
Syntax
matrixLog(A)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
AArray | MatrixA square matrix with positive eigenvalues
Returns
Array | Matrix — The principal matrix logarithm of A
Examples
matrixLog([[1
0
See Also
eigs inv det matrixRank
matrixPower
Raise a square matrix A to an integer power n. For n > 0 uses binary exponentiation (repeated squaring). For n = 0 returns the identity matrix. For n < 0 returns inv(A)^|n|.
Syntax
matrixPower(A | n)
Type Signatures
Array, number, Matrix, number
Parameters
NameTypeDescription
AArray | MatrixA square matrix
nnumberAn integer exponent
Returns
Array | Matrix — A^n
Examples
matrixPower([[1
1
See Also
multiply inv det eigs
matrixRank
Compute the numerical rank of a matrix using Singular Value Decomposition. The rank is the number of singular values exceeding a threshold tolerance.
Syntax
matrixRank(A) | matrixRank(A | tol)
Type Signatures
Array | Matrix, Array | Matrix, number
Parameters
NameTypeDescription
AArray | MatrixA two-dimensional matrix
tolnumberOptional tolerance for singular value threshold.
Returns
number — The numerical rank of A
Examples
matrixRank([[1
2
See Also
svd det nullSpace eigs
nullSpace
Compute an orthonormal basis for the null space (kernel) of a matrix A using Singular Value Decomposition. Returns an array of basis vectors corresponding to near-zero singular values.
Syntax
nullSpace(A) | nullSpace(A | tol)
Type Signatures
Array | Matrix, Array | Matrix, number
Parameters
NameTypeDescription
AArray | MatrixA two-dimensional matrix (m x n)
tolnumberOptional tolerance for near-zero singular values.
Returns
Array[] | Matrix[] — Array of basis vectors (each a plain Array or Matrix
Examples
nullSpace([[1
2
3
See Also
svd matrixRank inv eigs
ones
Create a matrix containing ones.
Syntax
ones(m) | ones(m | n)
Type Signatures
...number | BigNumber | string, Array | Matrix, string
Parameters
NameTypeDescription
size...(number|BigNumber) | ArrayThe size of each dimension of the matrix
formatstringThe Matrix storage format
Returns
Array | Matrix | number — A matrix filled with ones
Examples
ones(3)
ones(3
5)
ones([2
3
partitionSelect
Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.
Syntax
partitionSelect(x | k) | partitionSelect(x
Type Signatures
Array | Matrix, number, Array | Matrix, number, string
Parameters
NameTypeDescription
xMatrix | ArrayA one dimensional matrix or array to sort
kNumberThe kth smallest value to be retrieved zero-based index
Returns
* — Returns the kth lowest value.
Examples
partitionSelect([5
10
1
See Also
sort
pinv
Calculate the Moore–Penrose inverse of a matrix
Syntax
pinv(x)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
xnumber | Complex | Array | MatrixMatrix to be inversed
Returns
number | Complex | Array | Matrix — The inverse of `x`.
Examples
pinv([1
2; 3
4
See Also
inv
polarDecomposition
Compute the polar decomposition A = U * P of a square matrix A, where U is an orthogonal (unitary) matrix and P is a symmetric positive semidefinite matrix. Computed via SVD: A = U_svd * diag(S) * V^T, then U = U_svd * V^T and P = V * diag(S) * V^T.
Syntax
polarDecomposition(A)
Parameters
NameTypeDescription
AArray | MatrixA square matrix
Returns
{ U: Array|Matrix, P: Array|Matrix — }
Examples
polarDecomposition([[3
2
See Also
svd qr eigs
reshape
Reshape a multi dimensional array to fit the specified dimensions.
Syntax
reshape(x | sizes)
Type Signatures
Matrix, Array, Array, Array
Parameters
NameTypeDescription
xArray | Matrix | *Matrix to be reshaped
sizesnumber[]One dimensional array with integral sizes for
Returns
* | Array | Matrix — A reshaped clone of matrix `x`
Examples
reshape([1
2
3
4
5
See Also
size squeeze resize
resize
Resize a matrix.
Syntax
resize(x | size) | resize(x
Parameters
NameTypeDescription
xArray | Matrix | *Matrix to be resized
sizeArray | MatrixOne dimensional array with numbers
Returns
* | Array | Matrix — A resized clone of matrix `x`
Examples
resize([1
2
3
4
5
rotate
Returns a 2-D rotation matrix (2x2) for a given angle (in radians).
Syntax
rotate(w | theta) | rotate(w
Type Signatures
Array , number | BigNumber | Complex | Unit, Matrix , number | BigNumber | Complex | Unit, Array, number | BigNumber | Complex | Unit, Array | Matrix, Matrix, number | BigNumber | Complex | Unit, Array | Matrix
Parameters
NameTypeDescription
wArray | MatrixVector to rotate
thetanumber | BigNumber | Complex | UnitRotation angle
vArray | MatrixRotation axis
Returns
Array | Matrix — Multiplication of the rotation matrix and w
Examples
rotate([1
0
rotationMatrix
Returns a 2-D rotation matrix (2x2) for a given angle (in radians).
Syntax
rotationMatrix(theta) | rotationMatrix(theta | v)
Type Signatures
number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit, string, number | BigNumber | Complex | Unit, Array, number | BigNumber | Complex | Unit, Matrix, number | BigNumber | Complex | Unit, Array, string, number | BigNumber | Complex | Unit, Matrix, string
Parameters
NameTypeDescription
thetanumber | BigNumber | Complex | UnitRotation angle
vArray | MatrixRotation axis
formatstringResult Matrix storage format
Returns
Array | Matrix — Rotation matrix
Examples
rotationMatrix(pi / 2)
rotationMatrix(unit("45deg")
[0
0
1
See Also
cos sin
row
Return a row from a matrix or array.
Syntax
row(x | index)
Type Signatures
Array, number
Parameters
NameTypeDescription
valueArray | Matrix An array or matrix
rownumberThe index of the row
Returns
Array | Matrix — The retrieved row
Examples
A = [[1
2
rowReduce
Compute the Reduced Row Echelon Form (RREF) of a matrix using Gauss-Jordan elimination with partial pivoting. Each pivot element is scaled to 1, and all other entries in the pivot column are eliminated.
Syntax
rowReduce(matrix)
Type Signatures
Array | Matrix
Parameters
NameTypeDescription
matArray | MatrixThe input matrix (2D array or Matrix object)
Returns
Array — The RREF as a 2D array
Examples
rowReduce([[1
2
3
size
Calculate the size of a matrix.
Syntax
size(x)
Parameters
NameTypeDescription
xboolean | number | Complex | Unit | string | Array | MatrixA matrix
Returns
Array — A vector with size of `x`.
Examples
size(2.3)
size("hello world")
a = [1
2; 3
4; 5
sort
Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.
Syntax
sort(x) | sort(x | compare)
Type Signatures
Array, function, Matrix, function, Array, string, Matrix, string
Parameters
NameTypeDescription
xMatrix | ArrayA one dimensional matrix or array to sort
Returns
Matrix | Array — Returns the sorted matrix.
Examples
sort([5
10
1
See Also
map filter forEach
squeeze
Remove inner and outer singleton dimensions from a matrix.
Syntax
squeeze(x)
Parameters
NameTypeDescription
xMatrix | ArrayMatrix to be squeezed
Returns
Matrix | Array — Squeezed matrix
Examples
a = zeros(3
2
1)
size(squeeze(a))
b = zeros(1
subset
Get or set a subset of the entries of a matrix or
Syntax
value(index) | value(index) = replacement | subset(value
Type Signatures
Matrix, Index, Matrix, Index, any, any
Parameters
NameTypeDescription
matrixArray | Matrix | stringAn array, matrix, or string
indexIndex
replacement*An array, matrix, or scalar.
Returns
Array | Matrix | string — Either the retrieved subset or the updated matrix.
Examples
d = [1
2; 3
4
svd
Compute the Singular Value Decomposition A = U * diag(S) * V^T, returning an object { U, S, V } where U and V are orthogonal matrices and S is a vector of non-negative singular values in descending order.
Syntax
svd(A)
Parameters
NameTypeDescription
AArray | MatrixA two-dimensional matrix (m x n, m >= n)
Returns
{ U: Array|Matrix, S: number[], V: Array|Matrix — }
Examples
svd([[1
2
trace
Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.
Syntax
trace(A)
Parameters
NameTypeDescription
xArray | MatrixA matrix
Returns
number — The trace of `x`
Examples
A = [1
2
3; -1
2
3; 2
transpose
Transpose a matrix
Syntax
x\ | transpose(x)
Parameters
NameTypeDescription
xArray | MatrixMatrix to be transposed
Returns
Array | Matrix — The transposed matrix
Examples
a = [1
2
3; 4
5
6
zeros
Create a matrix containing zeros.
Syntax
zeros(m) | zeros(m | n)
Type Signatures
...number | BigNumber | string, Array | Matrix, string
Parameters
NameTypeDescription
size...(number|BigNumber) | ArrayThe size of each dimension of the matrix
formatstringThe Matrix storage format
Returns
Array | Matrix — A matrix filled with zeros
Examples
zeros(3)
zeros(3
5)
a = [1
2