Matrix Module
Matrix operations for linear algebra.
The Matrix module provides 2D matrix creation, arithmetic, decompositions, and DataFrame interop. Matrices are homogeneous: each matrix holds one element type — Float, Int, Decimal, or their Maybe variants.
Element types
Matrix Float— dense floating-point matrix (default for most constructors)Matrix Int— integer matrix; usefromRowsInt,zerosInt, etc.Matrix Decimal— arbitrary-precision decimal matrixMatrix (Maybe Float/Int/Decimal)— sparse/nullable matrix
Operators
+/-— element-wise add/sub (returnsResult (Matrix T) MatrixError)*— matrix multiplication (returnsResult (Matrix Float) MatrixError).*— Hadamard (element-wise) multiply./— element-wise divide (Matrix Int ./ Matrix Int→Matrix Float)
Common patterns
import Matrix
-- Create
let m = Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]]
Matrix.shape m -- (2, 2)
-- Arithmetic
m * m -- matmul, returns Result (Matrix Float) MatrixError
m .* m -- Hadamard product
-- Decompositions (Float only)
m |> Matrix.inv -- Result (Matrix Float) MatrixError
m |> Matrix.det -- Result Float MatrixError
m |> Matrix.svd -- (Matrix Float, [Float], Matrix Float)
Functions
Matrix.add
Matrix a -> Matrix a -> Result (Matrix a) MatrixError
Element-wise addition. Returns Err if shapes differ.
import Matrix
Matrix.add (Matrix.fromRows [[1.0, 2.0]]) (Matrix.fromRows [[3.0, 4.0]])Try itSee also: Matrix.sub, Matrix.scale
Matrix.chol
Matrix Float -> Result (Matrix Float) MatrixError
Cholesky decomposition. Returns the lower triangular L where A = L * L^T. Returns Err if not positive definite.
import Matrix
Matrix.fromRows [[4.0, 2.0], [2.0, 3.0]] |> Matrix.cholTry itSee also: Matrix.svd, Matrix.qr
Matrix.cols
Matrix a -> Int
Return the number of columns.
import Matrix
Matrix.zeros 3 4 |> Matrix.colsTry itSee also: Matrix.rows, Matrix.shape
Matrix.det
Matrix Float -> Result Float MatrixError
Compute the determinant. Returns Err if the matrix is not square.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.detTry itSee also: Matrix.inv, Matrix.rank
Matrix.dropCols
Matrix (Maybe Float) -> Matrix Float
Remove all columns that contain at least one Nothing value.
import Matrix
Matrix.fromRowsMaybe [[Just 1.0, Nothing, Just 3.0]] |> Matrix.dropCols |> Matrix.shapeTry itSee also: Matrix.dropRows, Matrix.fill
Matrix.dropRows
Matrix (Maybe Float) -> Matrix Float
Remove all rows that contain at least one Nothing value.
import Matrix
Matrix.fromRowsMaybe [[Just 1.0, Nothing], [Just 3.0, Just 4.0]] |> Matrix.dropRows |> Matrix.shapeTry itSee also: Matrix.dropCols, Matrix.fill
Matrix.eye
Int -> Matrix Float
Create an n×n identity matrix (Float).
import Matrix
Matrix.eye 3 |> Matrix.toRowsTry itSee also: Matrix.eyeInt, Matrix.zeros
Matrix.eyeInt
Int -> Matrix Int
Create an n×n identity matrix (Int).
import Matrix
Matrix.eyeInt 3 |> Matrix.shapeTry itSee also: Matrix.eye
Matrix.fill
Float -> Matrix (Maybe Float) -> Matrix Float
Replace all Nothing values with a fill value, returning a dense Float matrix.
import Matrix
Matrix.fromRowsMaybe [[Just 1.0, Nothing]] |> Matrix.fill 0.0 |> Matrix.toRowsTry itSee also: Matrix.dropRows, Matrix.dropCols, Matrix.fromRowsMaybeWith
Matrix.fromCols
[[a]] -> Matrix a
Create a matrix from a list of columns. All columns must have the same length.
import Matrix
Matrix.fromCols [[1.0, 3.0], [2.0, 4.0]] |> Matrix.toRowsTry itSee also: Matrix.fromColsInt, Matrix.fromColsDec, Matrix.fromRows
Matrix.fromColsDec
[[Decimal]] -> Matrix Decimal
Create a Decimal matrix from a list of columns.
import Matrix
Matrix.fromColsDec [[1.0d, 3.0d], [2.0d, 4.0d]] |> Matrix.shapeTry itSee also: Matrix.fromCols, Matrix.fromColsInt
Matrix.fromColsInt
[[Int]] -> Matrix Int
Create an integer matrix from a list of columns.
import Matrix
Matrix.fromColsInt [[1, 3], [2, 4]] |> Matrix.shapeTry itSee also: Matrix.fromCols, Matrix.fromColsDec
Matrix.fromDataFrame
DataFrame { .. } -> Result (Matrix Float) MatrixError
Convert a DataFrame with all-Float columns to a Matrix Float. Returns Err if any column contains nulls.
import Matrix
import DataFrame
let df = DataFrame.fromRecords [{ x = 1.0, y = 2.0 }, { x = 3.0, y = 4.0 }]
df |> Matrix.fromDataFrameTry itSee also: Matrix.fromDataFrameCols, Matrix.fromDataFrameMaybe, Matrix.toDataFrame
Matrix.fromDataFrameCols
[String] -> DataFrame { .. } -> Result (Matrix Float) MatrixError
Convert selected Float columns from a DataFrame to a Matrix Float.
import Matrix
import DataFrame
let df = DataFrame.fromRecords [{ a = 1.0, b = 2.0, c = 3.0 }]
df |> Matrix.fromDataFrameCols ["a", "c"]Try itSee also: Matrix.fromDataFrame
Matrix.fromDataFrameKeepNulls
DataFrame { .. } -> Matrix (Maybe Float)
Convert a DataFrame to a nullable Matrix (Maybe Float), preserving null positions as Nothing.
import Matrix
import DataFrame
let df = DataFrame.fromRecords [{ x = Just 1.0 }, { x = Nothing }]
df |> Matrix.fromDataFrameKeepNulls |> Matrix.get 1 0Try itSee also: Matrix.fromDataFrame, Matrix.fromDataFrameMaybe
Matrix.fromDataFrameMaybe
Float -> DataFrame { .. } -> Result (Matrix Float) MatrixError
Convert a DataFrame to a Matrix Float, replacing nulls with the given default.
import Matrix
import DataFrame
let df = DataFrame.fromRecords [{ x = Just 1.0 }, { x = Nothing }]
df |> Matrix.fromDataFrameMaybe 0.0Try itSee also: Matrix.fromDataFrame, Matrix.fromDataFrameKeepNulls
Matrix.fromFn
Int -> Int -> (Int -> Int -> a) -> Matrix a
Create a matrix by applying a function to each (row, col) index pair.
import Matrix
import Math
Matrix.fromFn 2 2 (|i : Int j : Int| (i + j) |> Math.toFloat) |> Matrix.toRowsTry itSee also: Matrix.zeros, Matrix.fromRows
Matrix.fromList
[a] -> Matrix a
Create a column vector (n×1 matrix) from a list. Element type is inferred from the list.
import Matrix
Matrix.fromList [1.0, 2.0, 3.0] |> Matrix.shapeTry itNotes: For unambiguous Int or Decimal construction, use fromListInt or fromListDec.
See also: Matrix.fromListInt, Matrix.fromListDec, Matrix.fromRows
Matrix.fromListDec
[Decimal] -> Matrix Decimal
Create a column vector (n×1 matrix) from a list of Decimal values.
import Matrix
Matrix.fromListDec [1.0d, 2.0d] |> Matrix.shapeTry itSee also: Matrix.fromList, Matrix.fromListInt
Matrix.fromListInt
[Int] -> Matrix Int
Create a column vector (n×1 matrix) from a list of integers.
import Matrix
Matrix.fromListInt [1, 2, 3] |> Matrix.shapeTry itSee also: Matrix.fromList, Matrix.fromListDec
Matrix.fromRows
[[a]] -> Matrix a
Create a matrix from a list of rows. All rows must have the same length.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.shapeTry itNotes: Returns Err String if rows have different lengths.
See also: Matrix.fromRowsInt, Matrix.fromRowsDec, Matrix.fromCols
Matrix.fromRowsDec
[[Decimal]] -> Matrix Decimal
Create a Decimal matrix from a list of rows.
import Matrix
Matrix.fromRowsDec [[1.0d, 2.0d]] |> Matrix.shapeTry itSee also: Matrix.fromRows, Matrix.fromRowsInt
Matrix.fromRowsInt
[[Int]] -> Matrix Int
Create an integer matrix from a list of rows.
import Matrix
Matrix.fromRowsInt [[1, 2], [3, 4]] |> Matrix.shapeTry itSee also: Matrix.fromRows, Matrix.fromRowsDec
Matrix.fromRowsMaybe
[[Maybe Float]] -> Matrix (Maybe Float)
Create a nullable Float matrix from a list of rows containing Maybe values.
import Matrix
Matrix.fromRowsMaybe [[Just 1.0, Nothing], [Just 3.0, Just 4.0]] |> Matrix.shapeTry itSee also: Matrix.fromRowsMaybeWith, Matrix.fill, Matrix.dropRows
Matrix.fromRowsMaybeWith
Float -> [[Maybe Float]] -> Matrix Float
Create a dense Float matrix, replacing Nothing values with a default.
import Matrix
Matrix.fromRowsMaybeWith 0.0 [[Just 1.0, Nothing]] |> Matrix.get 0 1Try itSee also: Matrix.fromRowsMaybe, Matrix.fill
Matrix.get
Int -> Int -> Matrix a -> Maybe a
Get the element at (row, col). Returns Nothing if out of bounds.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.get 1 0Try itSee also: Matrix.set
Matrix.hstack
Matrix a -> Matrix a -> Result (Matrix a) MatrixError
Concatenate two matrices horizontally (side by side). Row counts must match.
import Matrix
Matrix.hstack (Matrix.fromRows [[1.0], [2.0]]) (Matrix.fromRows [[3.0], [4.0]])Try itSee also: Matrix.vstack
Matrix.inv
Matrix Float -> Result (Matrix Float) MatrixError
Compute the matrix inverse. Returns Err if the matrix is singular or not square.
import Matrix
Matrix.fromRows [[2.0, 0.0], [0.0, 2.0]] |> Matrix.invTry itSee also: Matrix.det, Matrix.solve
Matrix.isSymmetric
Matrix (Maybe Float) -> Bool
Check if the matrix is symmetric (M[i,j] == M[j,i] for all present values).
import Matrix
Matrix.fromRowsMaybe [[Just 1.0, Just 2.0], [Just 2.0, Just 3.0]] |> Matrix.isSymmetricTry itSee also: Matrix.dropRows, Matrix.fill
Matrix.map
(a -> a) -> Matrix a -> Matrix a
Apply a function to every element. Infallible.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.map (|x| x * 2.0)Try itSee also: Matrix.scale
Matrix.mask
Matrix Float -> Matrix (Maybe Float)
Wrap every element in Just, converting a dense matrix to a nullable matrix.
import Matrix
Matrix.fromRows [[1.0, 2.0]] |> Matrix.mask |> Matrix.get 0 1Try itSee also: Matrix.fromRowsMaybe, Matrix.fill
Matrix.matmul
Matrix a -> Matrix a -> Result (Matrix a) MatrixError
Matrix multiplication (A * B). Returns Err if dimensions are incompatible. Supports Float, Int, and Decimal element types.
import Matrix
Matrix.matmul (Matrix.eye 2) (Matrix.fromRows [[3.0, 4.0], [5.0, 6.0]])Try itNotes: Use the * operator as shorthand for matrix multiplication.
See also: Matrix.transpose, Matrix.inv
Matrix.norm
Matrix Float -> Float
Frobenius norm (square root of sum of squared elements). Infallible.
import Matrix
Matrix.fromRows [[3.0, 4.0]] |> Matrix.normTry itSee also: Matrix.trace, Matrix.det
Matrix.ones
Int -> Int -> Matrix Float
Create a matrix of ones with the given dimensions.
import Matrix
Matrix.ones 2 2 |> Matrix.toRowsTry itSee also: Matrix.onesInt, Matrix.onesDec, Matrix.zeros
Matrix.onesDec
Int -> Int -> Matrix Decimal
Create a Decimal matrix of ones with the given dimensions.
import Matrix
Matrix.onesDec 2 2 |> Matrix.shapeTry itSee also: Matrix.ones, Matrix.onesInt
Matrix.onesInt
Int -> Int -> Matrix Int
Create an integer matrix of ones with the given dimensions.
import Matrix
Matrix.onesInt 2 2 |> Matrix.shapeTry itSee also: Matrix.ones, Matrix.onesDec
Matrix.outerAdd
Matrix Float -> Matrix Float -> Matrix Float
Compute the outer sum of two column vectors: M[i,j] = a[i] + b[j]. Both inputs must be column vectors (n×1).
import Matrix
let r = Matrix.rangeVec 0 3
Matrix.outerAdd r r |> Matrix.toRowsTry itNotes: Use this instead of fromFn when the entry formula is a sum of row and column indices. Runs in O(n×m) with no interpreter calls.
See also: Matrix.rangeVec, Matrix.fromFn
Matrix.qr
Matrix Float -> (Matrix Float, Matrix Float)
QR decomposition. Returns (Q, R).
import Matrix
let (q, r) = Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.qr
Matrix.shape qTry itSee also: Matrix.svd, Matrix.chol
Matrix.rangeVec
Int -> Int -> Matrix Float
Create a column vector [start, start+1, …, end] as Float. Both ends are inclusive.
import Matrix
Matrix.rangeVec 0 4 |> Matrix.toListTry itSee also: Matrix.outerAdd, Matrix.ones
Matrix.rank
Maybe Float -> Matrix Float -> Int
Estimate the numerical rank. Pass Nothing to use a default SVD-based tolerance, or Just tol to specify a custom tolerance.
import Matrix
Matrix.fromRows [[1.0, 0.0], [0.0, 1.0]] |> Matrix.rank NothingTry itSee also: Matrix.svd, Matrix.det
Matrix.rows
Matrix a -> Int
Return the number of rows.
import Matrix
Matrix.zeros 3 4 |> Matrix.rowsTry itSee also: Matrix.cols, Matrix.shape
Matrix.scale
a -> Matrix a -> Matrix a
Multiply every element by a scalar. Infallible.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.scale 2.0Try itSee also: Matrix.map, Matrix.add
Matrix.set
Int -> Int -> a -> Matrix a -> Result (Matrix a) MatrixError
Return a new matrix with the element at (row, col) replaced. Returns Err if out of bounds.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.set 0 0 9.0Try itSee also: Matrix.get
Matrix.shape
Matrix a -> (Int, Int)
Return the (rows, cols) dimensions of the matrix.
import Matrix
Matrix.fromRows [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] |> Matrix.shapeTry itSee also: Matrix.rows, Matrix.cols
Matrix.solve
Matrix Float -> Matrix Float -> Result (Matrix Float) MatrixError
Solve the linear system Ax = b. Returns Err if A is singular.
import Matrix
Matrix.solve (Matrix.fromRows [[2.0, 0.0], [0.0, 4.0]]) (Matrix.fromList [6.0, 8.0])Try itSee also: Matrix.inv, Matrix.det
Matrix.sub
Matrix a -> Matrix a -> Result (Matrix a) MatrixError
Element-wise subtraction. Returns Err if shapes differ.
import Matrix
Matrix.sub (Matrix.fromRows [[5.0, 6.0]]) (Matrix.fromRows [[1.0, 2.0]])Try itSee also: Matrix.add, Matrix.scale
Matrix.svd
Matrix Float -> (Matrix Float, [Float], Matrix Float)
Full SVD decomposition. Returns (U, singular_values, Vt).
import Matrix
let (u, s, vt) = Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.svd
Matrix.shape uTry itSee also: Matrix.svdThin, Matrix.qr
Matrix.svdThin
Int -> Matrix Float -> Result (Matrix Float, [Float], Matrix Float) MatrixError
Truncated SVD keeping k largest singular values. Returns Err if k > rank.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] |> Matrix.svdThin 1Try itSee also: Matrix.svd
Matrix.toCols
Matrix a -> [[a]]
Extract the matrix as a list of columns.
import Matrix
Matrix.fromCols [[1.0, 3.0], [2.0, 4.0]] |> Matrix.toColsTry itSee also: Matrix.toRows, Matrix.toList
Matrix.toDataFrame
[String] -> Matrix Float -> Result (DataFrame { .. }) MatrixError
Convert a Matrix Float to a DataFrame with the given column names. Returns Err if name count differs from column count.
import Matrix
import DataFrame
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.toDataFrame ["x", "y"]Try itSee also: Matrix.fromDataFrame
Matrix.toFloat
Matrix Int -> Matrix Float
Convert a Matrix Int to Matrix Float.
import Matrix
Matrix.fromRowsInt [[1, 2], [3, 4]] |> Matrix.toFloat |> Matrix.get 0 0Try itNotes: Decimal matrices cannot be converted to Float — use explicit Decimal arithmetic instead.
See also: Matrix.fromRowsInt
Matrix.toList
Matrix a -> Result [a] MatrixError
Extract elements as a flat list from a column or row vector. Returns Err if the matrix is not a vector (shape n×1 or 1×n).
import Matrix
Matrix.fromList [1.0, 2.0, 3.0] |> Matrix.toListTry itSee also: Matrix.fromList, Matrix.toRows
Matrix.toRows
Matrix a -> [[a]]
Extract the matrix as a list of rows.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.toRowsTry itSee also: Matrix.toCols, Matrix.toList
Matrix.trace
Matrix Float -> Result Float MatrixError
Sum of diagonal elements. Returns Err if not square.
import Matrix
Matrix.fromRows [[1.0, 2.0], [3.0, 4.0]] |> Matrix.traceTry itSee also: Matrix.det, Matrix.norm
Matrix.transpose
Matrix a -> Matrix a
Return the transpose of the matrix. Infallible.
import Matrix
Matrix.fromRows [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] |> Matrix.transpose |> Matrix.shapeTry itSee also: Matrix.matmul
Matrix.tridiag
Int -> Float -> Float -> Matrix Float
Create an n×n tridiagonal matrix with the given diagonal value and off-diagonal value. M[i,i] = diag, M[i,i±1] = off, all other entries are 0.
import Matrix
Matrix.tridiag 4 2.0 (-1.0) |> Matrix.toRowsTry itSee also: Matrix.eye, Matrix.fill, Matrix.fromFn
Matrix.vstack
Matrix a -> Matrix a -> Result (Matrix a) MatrixError
Concatenate two matrices vertically (on top of each other). Column counts must match.
import Matrix
Matrix.vstack (Matrix.fromRows [[1.0, 2.0]]) (Matrix.fromRows [[3.0, 4.0]])Try itSee also: Matrix.hstack
Matrix.zeros
Int -> Int -> Matrix Float
Create a matrix of zeros with the given dimensions.
import Matrix
Matrix.zeros 2 3 |> Matrix.shapeTry itSee also: Matrix.zerosInt, Matrix.zerosDec, Matrix.ones
Matrix.zerosDec
Int -> Int -> Matrix Decimal
Create a Decimal matrix of zeros with the given dimensions.
import Matrix
Matrix.zerosDec 2 3 |> Matrix.shapeTry itSee also: Matrix.zeros, Matrix.zerosInt
Matrix.zerosInt
Int -> Int -> Matrix Int
Create an integer matrix of zeros with the given dimensions.
import Matrix
Matrix.zerosInt 2 3 |> Matrix.shapeTry itSee also: Matrix.zeros, Matrix.zerosDec