librarylibs/Matrix/src/Matrix.xtl
Matrix: matrices -- identity, diagonal, trace, product, determinant, inverse, solving linear systems, orthonormal bases, projection onto a subspace and coordinates in a basis, eigenvalues and eigenvectors of a symmetric matrix, singular values and the best rank-k approximation and principal angles between row spaces. Import it with an alias of your choice: "mx:" u_se< "Matrix". Put libs/Matrix/src on XETAL_PATH ("just path"); the reference is libs/Matrix/docs. Names with l: are exported; those under h: are private to this file.
A matrix is a rank-2 array, rows first. The numerical functions (d_et, i_nverse, s_olve) work in Floats, by Gaussian elimination with partial pivoting; compare their results with Check's ch:n_ear. The transpose is the built-in o_\.
Basics
ˡi̲dentity : Num a => Int -> a
i_dentity n: the n by n identity matrix (1 then n zeros, cycled).
ˡi̲dentity ← { n → (n c̲at n) r̲eshape 1 c̲at n r̲eshape 0 }
ˡd̲iag : a -> a
d_iag m: the items on the main diagonal.
ˡd̲iag ← { m → k ← 'm̲in r̲/ s̲hape m (1 + (o̲ffsets k) × 1 + f̲irst r̲ev s̲hape m) s̲elect r̲avel m }
ˡm̲ul : Num a => a -> a -> a
a m_ul b: the matrix product (a matrix and a vector work too).
ˡm̲ul ← { a b → a '+ '× i̲nner b }
Solving
ʰs̲wapping : Int -> Int -> Int -> Int
The permutation of 1..n that swaps i and j.
ʰs̲wapping ← { n i j → r ← r̲ange n r + ((r = i) × j − i) + (r = j) × i − j }
ʰp̲ivot : Num a => Int -> a -> Int
The row (k..n) whose item in column k is largest in size.
ʰp̲ivot ← { k m → c ← a̲bs (k − 1) d̲rop k s̲elect₂ m k + (f̲irst g̲rade n̲eg c) − 1 }
ʰg̲j : Int -> Int -> Float -> Float
Gauss-Jordan on m (Float) for columns k..n of its first n: each column's pivot row moved up, scaled to 1, and the column cleared from every other row.
ʰg̲j ← { n k m → k > n ? m s ← ((n ʰs̲wapping k) k ʰp̲ivot m) s̲elect m r ← r̲ange t̲ally s v ← f̲irst k s̲elect k s̲elect₂ s ⍝ the pivot 0.000000000001 > a̲bs v ? @ p̲anic< "the matrix is singular: it has no inverse, and its system no unique solution" row ← (k s̲elect s) ÷ v c ← (k s̲elect₂ s) − f̲loat r = k ((n ʰg̲j k + 1) s − c '× t̲able row) }
ˡs̲olve : Num a => a -> a -> Float
b s_olve a: x with a m_ul x = b, for a square a; b is a vector or a matrix of right-hand sides (one per column). A singular a stops with error[panic] when a pivot is below 1e-12.
ˡs̲olve ← { b a → n ← t̲ally a x ← n d̲rop₂ ((n ʰg̲j 1) f̲loat a c̲at₂ b) (s̲hape b) r̲eshape x }
ˡi̲nverse : Num a => a -> Float
i_nverse a: the inverse of a square matrix.
ˡi̲nverse ← { a → (ˡi̲dentity t̲ally a) ˡs̲olve a }
Determinant
ʰd̲etF : Float -> Float
The determinant of a Float matrix m, by elimination: the first pivot times the determinant of what is left, negated for a row swap.
ʰd̲etF ← { m → n ← t̲ally m n = 1 ? f̲irst r̲avel m p ← 1 ʰp̲ivot m w ← ((n ʰs̲wapping 1) p) s̲elect m v ← f̲irst r̲avel w v = 0 ? 0.0 s ← f̲loat (p = 1) − p ≠ 1 r ← (1 d̲rop₂ 1 d̲rop w) − ((1 d̲rop f̲irst₂ w) ÷ v) '× t̲able 1 d̲rop f̲irst w s × v × ʰd̲etF r }
ˡd̲et : Num a => a -> Float
d_et a: the determinant of a square matrix.
ˡd̲et ← { a → ʰd̲etF f̲loat a }
Subspaces
ʰt̲ol : Any a => a -> Float
The tolerance of a dependent row: a remainder no longer than this fraction of its row's own length is counted as 0.
ʰt̲ol ← { u → 0.0000000001 }
ʰl̲ength : Num a => a -> Float
The length of the vector v.
ʰl̲ength ← { v → s̲qrt '+ r̲/ v × v }
ʰo̲rth : Num a => a -> a -> a
q o_rth v: v less its projection onto the rows of q (orthonormal, possibly none).
ʰo̲rth ← { q v → v − (q '+ '× i̲nner v) '+ '× i̲nner q }
ʰg̲s : Float -> Int -> Float -> Float
Modified Gram-Schmidt from row i of b on, the orthonormal rows so far in q: each row's remainder taken twice (once leaves rounding of the size of the projection; twice is orthogonal to the last digits) and kept, made unit length, unless it is within the tolerance of 0.
ʰg̲s ← { b i q → i > t̲ally b ? q v ← i s̲elect b w ← q ʰo̲rth q ʰo̲rth v r ← ʰl̲ength w r ≤ (ʰt̲ol @) × ʰl̲ength v ? ((b ʰg̲s i + 1) q) ((b ʰg̲s i + 1) q c̲at (1 c̲at t̲ally w) r̲eshape w ÷ r) }
ˡo̲rthonormal : Num a => a -> Float
o_rthonormal b: an orthonormal basis of the span of b's rows, as rows: modified Gram-Schmidt, twice, in row order, so the first row of the result is the first nonzero row of b made unit length. A row within 1e-10 of its own length of the span of the rows before it is dependent and dropped, so the result has as many rows as b's rank.
ˡo̲rthonormal ← { b → f ← f̲loat b ((f ʰg̲s 1) (0 c̲at f̲irst r̲ev s̲hape f) r̲eshape 0.0) }
ˡr̲ank : Num a => a -> Int
r_ank b: the dimension of the span of b's rows, the number of rows of its orthonormal basis (to the same tolerance).
ˡr̲ank ← { b → t̲ally ˡo̲rthonormal b }
ˡp̲roject : (Num a, Num b) => a -> b -> Float
b p_roject m: each row of m (or the vector m) projected onto the span of b's rows: its nearest point there, m Q' Q for Q the orthonormal basis of b's rows. b's rows need not be independent or orthonormal.
ˡp̲roject ← { b m → q ← ˡo̲rthonormal b ((f̲loat m) '+ '× i̲nner o̲\ q) '+ '× i̲nner q }
ˡr̲emainder : (Num a, Num b) => a -> b -> Float
b r_emainder m: what is left of m after its projection, m less b p_roject m: orthogonal to every row of b.
ˡr̲emainder ← { b m → (f̲loat m) − b ˡp̲roject m }
ˡc̲oordinates : (Num a, Num b) => a -> b -> Float
b c_oordinates m: the coordinates of each row of m (or the vector m) in the rows of b: c with c mx:m_ul b equal to m, for m in the span; for m outside it, the coordinates of its projection. b's rows must be independent (else the coordinates are not unique): solved in b's orthonormal basis Q, as c R = m Q' with R = b Q', so b b' is never inverted.
ˡc̲oordinates ← { b m → q ← ˡo̲rthonormal b (t̲ally q) < t̲ally b ? @ p̲anic< "the rows of the basis are dependent: coordinates in it are not unique" r ← (f̲loat b) '+ '× i̲nner o̲\ q a ← (f̲loat m) '+ '× i̲nner o̲\ q o̲\ (o̲\ a) ˡs̲olve o̲\ r }
Symmetric eigenvalues
ʰj̲acobiTol : Any a => a -> Float
Jacobi's stopping point: the off-diagonal part's length (Frobenius) at most this fraction of the whole matrix's.
ʰj̲acobiTol ← { u → 0.000000000000001 }
ʰj̲acobiSweeps : (Any a, Num b) => a -> b
The most sweeps Jacobi makes before it stops with a message.
ʰj̲acobiSweeps ← { u → 30 }
ʰf̲robenius : Num a => a -> Float
The length (Frobenius) of a matrix: every item squared, summed, rooted.
ʰf̲robenius ← { a → s̲qrt '+ r̲/ r̲avel a × a }
ʰo̲ff : Float -> Float
The off-diagonal part of the square matrix a, the diagonal zeroed.
ʰo̲ff ← { a → a × f̲loat 0 = ˡi̲dentity t̲ally a }
ʰr̲otation : Float -> Int -> Int -> Float
The rotation that zeroes item (p, q) of the symmetric a, as a full n by n matrix j (j' a j has 0 there): from tau = (a_qq - a_pp) / 2 a_pq, t = sign(tau) / (|tau| + sqrt(1 + tau^2)) (the smaller angle; an overflowing tau^2 makes t 0, no rotation), c = 1 / sqrt(1 + t^2), s = t c (Golub and Van Loan, sym.schur2). An item already 0 is left.
ʰr̲otation ← { a p q → n ← t̲ally a i ← f̲loat ˡi̲dentity n apq ← f̲irst q s̲elect p s̲elect a 0.0 = apq ? i tau ← ((f̲irst q s̲elect q s̲elect a) − f̲irst p s̲elect p s̲elect a) ÷ 2.0 × apq t ← (1.0 − 2.0 × f̲loat tau < 0.0) ÷ (a̲bs tau) + s̲qrt 1.0 + tau × tau c ← 1.0 ÷ s̲qrt 1.0 + t × t ep ← f̲loat (r̲ange n) = p eq ← f̲loat (r̲ange n) = q i + ((c − 1.0) × (ep '× t̲able ep) + eq '× t̲able eq) + (t × c) × (ep '× t̲able eq) − eq '× t̲able ep }
ʰs̲weep : (Float, Float) -> (Float, Float)
One cyclic sweep: a rotation for every pair p < q in row order, applied to a (j' a j) and gathered in v (v j); the state (a, v).
ʰs̲weep ← { (a, v) → n ← t̲ally a k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1 ps ← 1 + k d̲iv n qs ← 1 + k m̲od n r̲ot ← { (i, b, w) → j ← ((b ʰr̲otation i s̲elect ps) i s̲elect qs) (i + 1, (o̲\ j) ˡm̲ul b ˡm̲ul j, w ˡm̲ul j) } (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v) (b, w) }
ʰs̲weeps : Num a => a -> (Float, Float) -> (Float, Float)
Sweeps until the off-diagonal part is within the tolerance of the whole (or stop at the cap with a message); k sweeps made so far.
ʰs̲weeps ← { k (a, v) → (ʰf̲robenius ʰo̲ff a) ≤ (ʰj̲acobiTol @) × ʰf̲robenius a ? (a, v) k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps" (k + 1) ʰs̲weeps ʰs̲weep (a, v) }
ʰe̲igen : Num a => a -> (Float, Float)
The eigenvalues of the symmetric s, descending, and its eigenvectors as rows in the same order, each signed so its largest item (the first of equal ones) is positive. s must be square and symmetric (to 1e-12 of its largest item); it is not symmetrized.
ʰe̲igen ← { s → a ← f̲loat s n ← t̲ally a n̲ot (n c̲at n) m̲atch s̲hape a ? @ p̲anic< "the matrix is not square" big ← 'm̲ax r̲/ 0.0 c̲at r̲avel a̲bs a n̲ot '∧ r̲/ r̲avel (a̲bs a − o̲\ a) ≤ 0.000000000001 × big ? @ p̲anic< "the matrix is not symmetric: eigenvalues here are for symmetric matrices only" (d, v) ← 0 ʰs̲weeps (a, f̲loat ˡi̲dentity n) o ← g̲rade n̲eg ˡd̲iag d w ← o s̲elect o̲\ v ones ← n r̲eshape 1.0 hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones first ← hit × f̲loat 1.0 = '+ s̲\₂ hit sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first (o s̲elect ˡd̲iag d, w × sg '× t̲able ones) }
p̲anic< expands to
(⎕P̲ANIC ("the matrix is not symmetric: eigenvalues here are for symmetric matrices only"))
ˡe̲igenvalues : Num a => a -> Float
e_igenvalues s: the eigenvalues of the symmetric matrix s, largest first, by cyclic Jacobi.
ˡe̲igenvalues ← { s → (vals, _) ← ʰe̲igen s◆ vals }
ˡe̲igenvectors : Num a => a -> Float
e_igenvectors s: the eigenvectors of the symmetric matrix s, one per row, in the order of e_igenvalues; each of unit length, signed so its largest item is positive: s is (o_\ v) times diag(values) times v.
ˡe̲igenvectors ← { s → (_, vecs) ← ʰe̲igen s◆ vecs }
Singular values
ʰo̲rthogonal? : Truthy a => Float -> a
Whether the rows of a are orthogonal: every pair's dot product at most the tolerance times the product of their lengths.
ʰo̲rthogonal? ← { a → g ← a ˡm̲ul o̲\ a dg ← ˡd̲iag g '∧ r̲/ r̲avel (a̲bs ʰo̲ff g) ≤ (ʰj̲acobiTol @) × s̲qrt dg '× t̲able dg }
ʰs̲vdSweep : (Float, Float) -> (Float, Float)
One sweep of one-sided Jacobi on the rows of a: for every pair p < q, the rotation that makes rows p and q orthogonal (the Jacobi rotation of their Gram matrix, a a'), applied to a and gathered in v.
ʰs̲vdSweep ← { (a, v) → n ← t̲ally a k ← (w̲here r̲avel (r̲ange n) '< t̲able r̲ange n) − 1 ps ← 1 + k d̲iv n qs ← 1 + k m̲od n r̲ot ← { (i, b, w) → j ← (((b ˡm̲ul o̲\ b) ʰr̲otation i s̲elect ps) i s̲elect qs) (i + 1, (o̲\ j) ˡm̲ul b, (o̲\ j) ˡm̲ul w) } (_, b, w) ← (t̲ally k) 'r̲ot p̲ower (1, a, v) (b, w) }
ʰs̲vdSweeps : Num a => a -> (Float, Float) -> (Float, Float)
Sweeps until the rows are orthogonal (or stop at the cap).
ʰs̲vdSweeps ← { k (a, v) → ʰo̲rthogonal? a ? (a, v) k ≥ ʰj̲acobiSweeps @ ? @ p̲anic< "Jacobi did not converge in 30 sweeps" (k + 1) ʰs̲vdSweeps ʰs̲vdSweep (a, v) }
ʰs̲vdTall : Float -> (Float, Float, Float)
The thin SVD of m with at least as many rows as columns: one-sided Jacobi on the rows of m' (m itself is never squared), so the rows end orthogonal, of lengths the singular values, along the left singular vectors; v gathers the rotations, the right ones. Largest first, each v row signed so its largest item is positive.
ʰs̲vdTall ← { m → n ← f̲irst r̲ev s̲hape m (a, v) ← 0 ʰs̲vdSweeps (o̲\ m, f̲loat ˡi̲dentity n) s ← s̲qrt '+ r̲/₂ a × a o ← g̲rade n̲eg s ones ← n r̲eshape 1.0 ss ← o s̲elect s u ← (o s̲elect a) ÷ (ss + f̲loat ss = 0.0) '× t̲able (t̲ally f̲irst a) r̲eshape 1.0 w ← o s̲elect v hit ← f̲loat (a̲bs w) = ('m̲ax r̲/₂ a̲bs w) '× t̲able ones first ← hit × f̲loat 1.0 = '+ s̲\₂ hit sg ← 1.0 − 2.0 × f̲loat 0.0 > '+ r̲/₂ w × first (u × sg '× t̲able (t̲ally f̲irst u) r̲eshape 1.0, ss, w × sg '× t̲able ones) }
ˡs̲vd : Num a => a -> (Float, Float, Float)
s_vd m: the singular value decomposition, (u, s, v) with m equal to (o_\ u) mx:m_ul diag(s) mx:m_ul v: s the singular values, largest first, as many as m's smaller side; u's rows the left singular vectors, v's the right ones (a zero singular value has a zero row in u for tall/square m, in v for wide m). One-sided Jacobi on m or m'.
ˡs̲vd ← { m → f ← f̲loat m (r, c) ← (f̲irst s̲hape f, f̲irst r̲ev s̲hape f) r ≥ c ? ʰs̲vdTall f (u, s, v) ← ʰs̲vdTall o̲\ f (v, s, u) }
ˡs̲ingular : Num a => a -> Float
s_ingular m: the singular values of the matrix m, largest first, as many as its smaller side.
ˡs̲ingular ← { m → (_, s, _) ← ˡs̲vd m◆ s }
ˡt̲runcate : Num a => Int -> a -> Float
k t_runcate m: the best approximation of m of rank at most k (Eckart and Young: nearest in both the Frobenius and the spectral norm), its k largest singular values kept and the rest made 0; m itself when k is at least its smaller side.
ˡt̲runcate ← { k m → (u, s, v) ← ˡs̲vd m j ← k m̲in t̲ally s (o̲\ j t̲ake u) ˡm̲ul ((j t̲ake s) '× t̲able (f̲irst r̲ev s̲hape v) r̲eshape 1.0) × j t̲ake v }
Principal angles
ʰa̲ngleMatrix : Num a => a -> Float
A finite rank-2 matrix for subspace comparison, converted to Float. Scale each nonzero row by its largest magnitude before taking norms.
ʰa̲ngleMatrix ← { a → n̲ot 2 = t̲ally s̲hape a ? @ p̲anic< "principal angles require rank-2 matrices" f ← f̲loat a n̲ot '∧ r̲/ r̲avel (f − f) = 0.0 ? @ p̲anic< "principal angles require finite input" columns ← f̲irst r̲ev s̲hape f 0 = columns ? f magnitude ← 'm̲ax r̲/₂ a̲bs f divisor ← magnitude + f̲loat magnitude = 0.0 f ÷ divisor '× t̲able columns r̲eshape 1.0 }
ʰa̲ngles : Float -> Float -> Float
Principal angles for orthonormal rows p,q with dim(p) <= dim(q). The right singular vectors of q p' give principal directions in p, including zero cosine values. Their residuals off q give the sines.
ʰa̲ngles ← { p q → (_, cosines, right) ← ˡs̲vd q ˡm̲ul o̲\ p directions ← right ˡm̲ul p residual ← directions − (directions ˡm̲ul o̲\ q) ˡm̲ul q sine ← s̲qrt '+ r̲/₂ residual × residual cosine ← 0.0 m̲ax 1.0 m̲in cosines ⍝ Nonnegative atan2 by its half-angle form, finite even at c=0. angle ← 2.0 × a̲tan sine ÷ (s̲qrt (sine × sine) + cosine × cosine) + cosine (g̲rade angle) s̲elect angle }
ˡa̲ngles : (Num a, Num b) => a -> b -> Float
a a_ngles b: ascending principal angles in radians between row spaces, as many as the smaller rank. Orthonormal bases use the 1e-10 relative row-dependence tolerance. Zero-rank inputs give an empty Float vector. SVD cosines plus residual sines preserve small angles without acos(1).
ˡa̲ngles ← { a b → x ← ʰa̲ngleMatrix a y ← ʰa̲ngleMatrix b n̲ot (f̲irst r̲ev s̲hape x) = f̲irst r̲ev s̲hape y ? @ p̲anic< "principal-angle matrices must have the same column count" (0 = t̲ally x) ∨ (0 = t̲ally y) ∨ 0 = f̲irst r̲ev s̲hape x ? 0 r̲eshape 0.0 p ← ˡo̲rthonormal x q ← ˡo̲rthonormal y (0 = t̲ally p) ∨ 0 = t̲ally q ? 0 r̲eshape 0.0 (t̲ally p) ≤ t̲ally q ? p ʰa̲ngles q q ʰa̲ngles p }