cl-simple-matrix

2026-11-29

Functions to work with matrices.

Upstream URL

codeberg.org/glv/cl-simple-matrix

Author

Guillaume LE VAILLANT

License

GPL-3
README
simple-matrix

1Description

simple-matrix is a Common Lisp library implementing some functions towork with matrices.

This library is designed to be generic, to be used for a few simple computations. If you need something to work very fast on a lot of big matrices, this is not the library you are looking for.

Matrices are represented as arrays with two dimensions containing elements of type number. So you can have a matrix containing integers, rationals, floats and complexes at the same time if you want.

2License

simple-matrix is released under the GPL-3 license or later. See theLICENSE file for details.

3API

After putting the library in a place where your Common Lisp system can see it,it can be loaded with the usual:
  (asdf:load-system "simple-matrix")

As the code is in a single file, you could also just load it directly:

  (load "/path/to/simple-matrix.lisp")

The functions will then be available in the simple-matrix package.

Note: if your are using CLISP as implementation of Common Lisp, set the custom:*floating-point-contagion-ansi* parameter to t, otherwise some functions could have precision issues.

3.1Parameters

Numbers with an amplitude lesser than the *epsilon* parameter will beconsidered equal to 0 by some functions (1.0d-6 by default).

The *qr-variant* parameter indicates which algorithm to use for the QR decomposition:

  • :householder to use Householder transformations and return a full QRdecomposition. This is the variant used by default.
  • :householder-reduced to use Householder transformations and returna reduced QR decomposition.
  • :givens to use Givens rotations and return a full QR decomposition.This can make computations faster for matrices containing a lot of zeros.
  • :givens-reduced to use Givens rotations and return a reduced QRdecomposition.
  • :gram-schmidt to use the Gram-Schmidt process and return a reduced QRdecomposition.
The reduced QR variants can be useful, for example, to make computations fasterfor the least squares method on a matrix with a lot more rows than columns, orto compute a reduced singular value decomposition.

The *schur-variant* parameter indicates which variant of the Schur decomposition to use. It can be :complex (the default), or :real.

The *max-iterations* parameter indicates the maximum number of iterations used to compute some functions (like msqrt, mschur, meigen, mqz or msvd). It is 1000 by default. It can be nil to make the computation stop only when the function considers it has converged (which could be never). If an iterative algorithm fails to converge before *max-iterations* is reached, a convergence-error is signaled.

The *diagonalize-p* parameter indicates if some functions (like mexp or msqrt) will try to diagonalize the matrix to compute their result. It is t by default.

3.2Matrix creation and element access

As matrices are represented as arrays with two dimensions, their elements canbe accessed using the regular aref function.
  (matrix r c &optional elements by-column) => matrix
Create a matrix with r rows and c columns. If the elements are provided,use them to fill the matrix either row by row if by-column is nil(the default), or column by column if by-column is t. The elements can beprovided as a list, a vector or a matrix. If elements is a matrix, it will beread row by row. If the elements are not provided, the matrix will be full ofzeros.
  (vec->mat v) => matrix
Convert the vector v to a column matrix.
  (mat->vec m) => vector
Convert the column matrix M to a vector.
  (mvec m) => matrix
Return a column matrix containing the concatenated columns of the matrix M.
  (mcopy m) => matrix
Return a copy of the matrix M.
  (mround m &optional precision) => matrix
Return a copy of the matrix M with its elements rounded to some precision(*epsilon* by default).
  (msub m &key row-start row-end column-start column-end) => matrix
Return a submatrix of M, starting at row row-start and columncolumn-start, and ending before row row-end and column column-end.This function is setf-able.
  (mrow m i) => vector
Return row i of matrix M as a vector.This function is setf-able.
  (mcol m j) => vector
Return column j of matrix M as a vector.This function is setf-able.
  (mdiag m) => vector
Return diagonal of matrix M as a vector.This function is setf-able.
  (mminor m i j) => matrix
Return the matrix M with row i and column j removed.

3.3Common matrices

  (mi n) => matrix
Create an identity matrix with n rows and n columns.
  (mrand r c) => matrix
Create a matrix with r rows and c columns whose elements are random valuesbetween -1 and 1.
  (mpermutation p) => matrix
Return the matrix representing the permutation p.If Q is the permutation matrix for p, row i of a matrix M will becomerow p(i) in QM, and column p(j) will become column j in MQ.
  (mprojection m) => matrix
Return the matrix representing the orthogonal projection on the image(column space) of the matrix M.
  (mreflection m) => matrix
Return the matrix representing the reflection across the hyperplanecontaining the origin orthogonal to the column matrix M.
  (mrotation m a) => matrix
Return the matrix representing the rotation of a radians in the plane definedby the image (column space) of the matrix M.

Note: changing the order of the 2 columns of M has the same effect as negating the rotation angle.

  (mtoeplitz a &optional b) => matrix
Return the Toeplitz matrix whose first column is A and first row is B.If B is not specified, the returned matrix will be symmetric.
  (mhankel a &optional b) => matrix
Return the Hankel matrix whose first column is A and last row is B.If B is not specified, the returned matrix will have zeros below the mainanti-diagonal.
  (mfrank n) => matrix
Return the Frank matrix with n rows and n columns.
  (mhilbert n) => matrix
Return the Hilbert matrix with n rows and n columns.
  (mpascal n) => matrix
Return the Pascal matrix with n rows and n columns.
  (mwilkinson n) => matrix
Return the Wilkinson matrix with n rows and n columns.
  (mhadamard n) => matrix
Return a Hadamard matrix with n rows and n columns.
  (mvandermonde m &optional n) => matrix
Return the Vandermonde matrix with n columns based on the column matrix M.If n is not specified the returned matrix will be square.
  (mcirculant m) => matrix
Return the circulant matrix whose first row is M.
  (mcompanion p) => matrix
Return the companion matrix of the polynomial whose coefficients are in pin order of increasing degree.
  (mjacobian f x &optional dx) => matrix
Return the jacobian matrix for the vector-valued function f evaluated at X.f must take a column matrix as argument and return a column matrix. A stepDX will be used to compute the finite differences. It can be a column matrixwith the same size as X or a real number.
  (mhessian f x &optional dx) => matrix
Return the hessian matrix for the vector-valued function f evaluated at X.f must take a column matrix as argument and return a column matrix. A stepDX will be used to compute the finite differences. It can be a column matrixwith the same size as X or a real number.If f takes a column matrix with n rows and returns a column matrix withm rows, the hessian matrix will have m*n rows and n columns.The n by n hessian matrix for the first component of f will startat row 0, the n by n hessian matrix for the second component will startat row n, etc.

3.4Predicates

These functions take *epsilon* into consideration.
  (m= m &rest matrices) => boolean
Return t if the matrices are equal, and nil otherwise.
  (mreal-p m) => boolean
Return t if the matrix M contains only real numbers, and nil otherwise.
  (mdiagonal-p m) => boolean
Return t if M is a diagonal matrix, and nil otherwise.
  (mupper-triangular-p m) => boolean
Return t if the matrix M is in upper triangular form, and nil otherwise.
  (mlower-triangular-p m) => boolean
Return t if the matrix M is in lower triangular form, and nil otherwise.
  (mhessenberg-p m) => boolean
Return t if the matrix M is in upper Hessenberg form, and nil otherwise.
  (mbidiagonal-p m) => boolean
Return t if the matrix M is in upper bidiagonal form, and nil otherwise.
  (msymmetric-p m) => boolean
Return t if M is a symmetric matrix, and nil otherwise.
  (mhermitian-p m) => boolean
Return t if M is a hermitian matrix, and nil otherwise.
  (mrow-echelon-p m) => boolean
Return t if the matrix M is in row echelon form, and nil otherwise.
  (mpositive-definite-p m) => boolean
Return t if the matrix M is hermitian positive definite,and nil otherwise.

3.5Basic operations

  (m+ m &rest matrices) => matrix
Return the addition of matrices to the matrix M.
  (m- m &rest matrices) => matrix
Return the subtraction of matrices from the matrix M.
  (m* m &rest matrices) => matrix
Return the product of the matrix M and matrices.
  (mc+ m x) => matrix
Return a matrix with the all elements of M incremented by a constant x.
  (mc- m x) => matrix
Return a matrix with the all elements of M decremented by a constant x.
  (mc* m x) => matrix
Return the mutiplication of the matrix M by a constant x.
  (mc/ m x) => matrix
Return the division of the matrix M by a constant x.
  (me* m &rest matrices) => matrix
Return the Hadamard (element-wise) product of the matrix M and matrices.
  (me/ m &rest matrices) => matrix
Return the element-wise division of the matrix M by matrices.
  (mk* m &rest matrices) => matrix
Return the Kronecker product of the matrix M and matrices.
  (m.* m1 m2) => number
Return the Frobenius scalar product of the matrices M1 and M2.
  (mx* m1 m2) => matrix
Return the vector product of the column matrices M1 and M2.M1 and M2 must have 3 or 7 rows.
  (mnorm m &optional variant) => number
Return the norm of the matrix M.The variant can be:
  • :frobenius (the default)
  • :max
  • :row or :infinity
  • :column or 1
  • :spectral or 2
  • :nuclear
  (mcond m) => number
Return the condition number of the matrix M (in 2-norm).If the condition number if infinite, nil is returned.
  (mconj m) => matrix
Return the complex conjugate of the matrix M.
  (mt m) => matrix
Return the transpose of the matrix M.
  (mct m) => matrix
Return the conjugate transpose of the matrix M.
  (mtr m) => number
Return the trace of the matrix M.
  (mre m &optional reduced-p) => matrix, number
Return a row echelon form of the matrix M and the product of its diagonalelements (that is the determinant of M if it is square).If reduced-p is t, the reduced row echelon form is returned.
  (minv m) => matrix, number
Return the inverse of the matrix M and the determinant of M.If M is not invertible, nil and 0 will be returned.
  (mpinv m) => matrix
Return the Moore-Penrose pseudoinverse of the matrix M.
  (mcom m) => matrix
Return the cofactor matrix of M.
  (mdet m) => number
Return the determinant of the matrix M.
  (mpoly m) => vector
Return the coefficients of the characteristic polynomial of the matrix Min order of increasing degree.
  (mrk m) => number
Return the rank of the matrix M.
  (mker m) => matrix
Return a matrix whose columns form an orthonormal basis forthe kernel (null space) of the matrix M.
  (mim m) => matrix
Return a matrix whose columns form an orthonormal basis forthe image (column space) of the matrix M.
  (mortho m) => matrix
Return a matrix whose columns form an orthonormal basis forthe orthogonal complement of the image (column space) of the matrix M.
  (munion a b) => matrix
Return a matrix whose columns form an orthonormal basis for the unionof the images (column spaces) of the matrices A and B.
  (minter a b) => matrix
Return a matrix whose columns form an orthonormal basis for the intersectionof the images (column spaces) of the matrices A and B.
  (mexpt m n) => matrix
Return the matrix M raised to the nth power.
  (mexp m &optional iterations diagonalize-p) => matrix
Return the exponential of the matrix M. If diagonalize-p is t (thedefault), the function will try to diagonalize M to compute its exponential.If it fails, or if diagonalize-p is nil, a Padé approximant will be usedinstead.
  (mlog m &optional iterations diagonalize-p) => matrix
Return a logarithm of the matrix M. If diagonalize-p is t (the default),the function will try to diagonalize M to compute its logarithm. If it fails,or if diagonalize-p is nil, a Padé approximant will be used instead. If nologarithm has been found, nil is returned.
  (msqrt m &optional iterations diagonalize-p) => matrix
Return a square root of the matrix M. If diagonalize-p is t (thedefault), the function will try to diagonalize M to compute its square root.If it fails, or if diagonalize-p is nil, the Denman-Beavers iteration willbe used instead. If no square root has been found, nil is returned.
  (msign m &optional iterations diagonalize-p) => matrix
Return the sign of the matrix M. If diagonalize-p is t (the default), thefunction will try to diagonalize M to compute its sign. If it fails, or ifdiagonalize-p is nil, Newton's method will be used instead. If no signmatrix has been found, nil is returned.
  (mfun m f &optional iterations) => matrix
Apply the matrix function f to the matrix M. f must take a number asargument and return a number. If M can't be diagonalized to apply f,nil is returned.
  (mhorner m p) => matrix
Apply the matrix polynomial whose coefficients are in p in order ofincreasing degree to the matrix M.
  (mefun m f) => matrix
Return a matrix created by applying the function f to each element of thematrix M. f must return a number, and take 3 numbers as arguments:
  • the element of M
  • the row index of the element
  • the column index of the element.
  (mehorner m p) => matrix
Apply the polynomial whose coefficients are in p in order ofincreasing degree to each element of the matrix M.

3.6Decompositions

  (mqr m &optional variant) => matrix, matrix
QR decomposition.Return 2 matrices Q and R, where Q is orthonormal, R is uppertriangular and M = QR.If variant is :householder or :givens, a full QR decomposition isreturned.If variant is :householder-reduced, :givens-reduced or :gram-schmidt,a reduced QR decomposition is returned.
  (mlq m) => matrix, matrix
LQ decomposition.Return 2 matrices L and Q, where L is lower triangular, Q isorthonormal and M = LQ.
  (mrq m) => matrix, matrix
RQ decomposition.Return 2 matrices R and Q, where R is upper triangular, Q isorthonormal, and M = RQ.
  (mql m) => matrix, matrix
QL decomposition.Return 2 matrices Q and L, where Q is orthonormal, L is lowertriangular and M = QL.
  (mrrqr m) => matrix, matrix, matrix
Rank revealing QR decomposition.Return 3 matrices Q, R and P, where Q is orthonormal,R is in row echelon form, P is a permutation matrix, and MP = QR."
  (mlu m) => matrix, matrix
LU decomposition.Return 2 matrices L and U, where L is lower triangular, U is uppertriangular and M = LU.If a LU decomposition is not possible, nil and nil are returned.
  (mlup m) => matrix, matrix, matrix
LU decomposition with row permutation.Return 3 matrices L and U and P, where L is lower triangular, U isupper triangular, P is a permutation matrix and PM = LU.
  (mcholesky m) => matrix
Cholesky decomposition.Return a lower triangular matrix L such that M = LL*. M must bea hermitian matrix. If a Cholesky decomposition is not possible,nil is returned.
  (mldl m) => matrix, matrix
Alternative Cholesky decomposition.Return 2 matrices L and D, where L is lower triangular with ones on thediagonal, D is diagonal, and M = LDL*. M must be a hermitian matrix. Ifan alternative Cholesky decomposition is not possible, nil and nil arereturned.
  (mrf m) => matrix, matrix
Rank decomposition.Return 2 matrices C anf F, where the number of columns of C and the numberof rows of F are equal to the rank of M, and M = CF.
  (mhessenberg m) => matrix, matrix
Return 2 matrices H and Q, where H is in upper Hessenberg form, Q isunitary, and M = QHQ*."
  (mbidiagonal m) => matrix, matrix, matrix
Return 3 matrices U, B and V, where B is upper bidiagonal, U and Vare unitary, and M = UBV*.
  (mbalance m) => matrix, matrix
Return 2 matrices A and D, such that A is a balanced matrix, D isdiagonal, and M = DAD⁻¹.
  (mschur m &optional iterations variant) => matrix, matrix
Schur decomposition.Return 2 matrices U and Q, where U is upper triangular with theeigenvalues on the diagonal, Q is unitary, and M = QUQ*. If variant is:real instead of :complex, U will be quasi-triangular if M has complexeigenvalues.
  (mschur-reordering u indexes) => matrix, matrix
Given an upper triangular matrix U, return 2 matrices V and Q such thatV is upper triangular, Q is unitary and U = QVQ* with the top left blockof V containing the eigenvalues that are at some indexes in the diagonal ofU.
  (meigen m &optional iterations) => matrix, matrix
Eigen decomposition.Return a diagonal matrix D with the eigenvalues of the matrix M on thediagonal, and a matrix P whose columns are eigenvectors. If P isinvertible, M = PDP⁻¹.
  (meigenvector u a &optional b iterations) => matrix
Return an eigenvector for the eigenvalue u. The returned column matrix X issuch that AX = uX if B is not specified, or such that AX = uBX if B isspecified.
  (mqz a b &optional iterations) => matrix, matrix, matrix, matrix
Generalized Schur decomposition.Return 4 matrices R, S, Q and Z, where R and S are uppertriangular, Q and Z are unitary, A = QRZ* and B = QSZ*.
  (mqz-reordering r s indexes) => matrix, matrix, matrix, matrix
Given 2 matrices R and S in upper triangular form, return 4 matrices U,V, Q and Z such that U and V are upper triangular, Q and Z areunitary, R = QUZ* and S = QVZ* with the top left blocks of U and Vcontaining the generalized eigenvalues that are at some indexes in thediagonals of R and S.
  (mutv m) => matrix, matrix, matrix
Complete orthogonal decomposition.Return 3 matrices U, T and V, where U and V are orthonormal,T is lower triangular and in column echelon form, and M = UTV*.
  (msvd m &optional iterations) => matrix, matrix, matrix
Singular value decomposition.Return 3 matrices U, S and V, where U and V are orthonormal,S is diagonal with the singular values on the diagonal, and M = USV*.If *qr-variant* is :householder-reduced or :givens-reduced,an economy SVD is returned instead of the full SVD.
  (mgsvd m &optional iterations) => matrix, matrix, matrix, matrix, matrix
Generalized singular value decomposition.Return 5 matrices R, S, U, V and W, where R is diagonal,S is diagonal or bottom-right-diagonal, U and V are orthonormal,A = URW* and B = VSW*.
  (mpolar m) => matrix, matrix
Polar decomposition.Return 2 matrices U and H, where U is unitary, H is positivesemi-definite hermitian, and M = UH.
  (mjordan m &optional eigenvalues) => matrix, matrix
Jordan canonical form.Return 2 matrices J and P, where J is in Jordan canonical form,P is invertible, and M = PJP⁻¹. The eigenvalues of M can be specified(an eigenvalue with multiplicity n must be repeated n times),otherwise they will be computed with the mschur function.If no Jordan canonical form has been found (because of numerical inaccuracycaused by floating point numbers), nil and nil are returned.

3.7Solving equations

  (mbackward-substitute u y) => matrix
Return a column matrix X such that UX = Y, where U is upper triangularin row echelon form. If there is no solution, nil is returned.
  (mforward-substitute l y) => matrix
Return a column matrix X such that LX = Y, where L is lower triangular.If L has a 0 in its main diagonal or if there is no solution,nil is returned.
  (msolve m y) => matrix, boolean
System of linear equations.Return a column matrix X such that MX = Y. The second returned value is tif X is the unique solution, and nil otherwise. If no solution has beenfound, nil and nil are returned.
  (msolve-roots m) => matrix
Roots of a polynomial.Return a column matrix containing the roots of a polynomial. M can bea companion matrix of the polynomial, or a sequence containing the coefficientsof the polynomial in order of increasing degree.
  (msolve-ode m x0 y u) => matrix
System of ordinary differential equations.Return the column matrix X(u), knowing that dX(t)/dt = MX(t) + Yand X(0) = X0. If no solution has been found, nil is returned.
  (msolve-sylvester a b c) => matrix, boolean
Sylvester equation.Return a matrix X such that AX + XB = C. The second returned value is tif X is the unique solution, and nil otherwise. If no solution has beenfound, nil and nil are returned.
  (msolve-axb y &rest matrices) => matrix, boolean
Generalized Sylvester equation.Given a matrix Y and square matrices /A/, B, C, D, E, F, ...,return a matrix X such that AXB + CXD + EXF + ... = Y. The second returnedvalue is t if X is the unique solution, and nil otherwise. If no solutionhas been found, nil and nil are returned.
  (msolve-riccati a b c) => matrix
Continuous time algebraic Riccati equation.Return a matrix X such that AᵀX + XA - XBX + C = 0.If no solution has been found, nil is returned.
  (msolve-riccati-discrete a b q r) => matrix
Discrete time algebraic Riccati equation.Return a matrix X such that AᵀXA - X - AᵀXB(R + BᵀXB)⁻¹BᵀXA + Q = 0.If no solution has been found, nil is returned.

3.8Least squares

  (mls m y) => matrix
Least squares.Return a column matrix X minimizing the norm of MX - Y.
  (mls-axb y &rest matrices) => matrix
Least squares solution of generalized Sylvester equation.Given a matrix Y and matrices /A/, B, C, D, E, F, ...,return a matrix X minimizing the norm of AXB + CXD + EXF + ... - Y.
  (mls+ m y) => matrix
Non-negative least squares.Return a column matrix X minimizing the norm of MX - Y,and such that the elements of X are greater than or equal to 0.
  (mlse m y a b) => matrix
Least squares with equality constraints.Return a column matrix X minimizing the norm of MX - Y,and such that AX = B.If no solution has been found, nil is returned.
  (mlsi m y a b) => matrix
Least squares with inequality constraints.Return a column matrix X minimizing the norm of MX - Y,and such that AX ≤ B.If no solution has been found, nil is returned.

Note: if M doesn't have full column rank, mlsi will return an approximate solution or fail to find a solution even if it exists.

  (mtls m y &optional error-free-columns) => matrix, matrix, matrix
Total least squares.Return a column matrix X minimizing the norms of the error matrices Eand F, where (M + E)X = Y + F. The second and third returned values are Eand F. If no solution has been found, nil, nil and nil are returned.The function will consider that there is no uncertainty on the firsterror-free-columns columns of M.

3.9Optimization

  (mlpe p a b) => matrix
Linear optimization with equality constraints.Return a column matrix X minimizing PᵀX, such that X ≥ 0 and AX = B.The second returned value is PᵀX.If no solution has been found, nil and nil are returned.
  (mlpi p a b) => matrix
Linear optimization with inequality constraints.Return a column matrix X minimizing PᵀX, such that X ≥ 0 and AX ≤ B.The second returned value is PᵀX.If no solution has been found, nil and nil are returned.
  (mqp q p) => matrix
Quadratic optimization.Return a column matrix X minimizing ½XᵀQX + PᵀX.Q must be symmetric positive definite.The second returned value is ½XᵀQX + PᵀX.
  (mqp+ q p) => matrix
Non-negative quadratic optimization.Return a column matrix X minimizing ½XᵀQX + PᵀX,and such that the elements of X are greater than or equal to 0.Q must be symmetric positive definite.The second returned value is ½XᵀQX + PᵀX.
  (mqpe q p a b) => matrix
Quadratic optimization with equality constraints.Return a column matrix X minimizing ½XᵀQX + PᵀX, and such that AX = B.Q must be symmetric positive definite.The second returned value is ½XᵀQX + PᵀX.If no solution has been found, nil and nil are returned.
  (mqpi q p a b) => matrix
Quadratic optimization with inequality constraints.Return a column matrix X minimizing ½XᵀQX + PᵀX, and such that AX ≤ B.Q must be symmetric positive definite.The second returned value is ½XᵀQX + PᵀX.If no solution has been found, nil and nil are returned.

3.10Data analysis

  (mpca x &optional n center-p) => matrix, matrix, vector, vector
Principal component analysis.Return 2 matrices C and S and 2 vectors V and R, where the columnsof C are principal component coefficients (loadings) of the data matrix X,S is the score matrix, V contains principal component variances and Rcontains the ratios of each principal component variance relative to the totalvariance.If n is specified, at most n principal components will be computed.Otherwise the number of computed principal components will be determined fromthe singular values of X and *epsilon*.If center-p is t (the default), the data in X will be centered beforebeing analyzed.This function assumes that the rows of X are observations and the columnsare variables.
  (mdmd x y &optional n) => matrix, matrix, matrix
Exact dynamic mode decomposition.From a pair of data snapshot matrices X and Y such that MX = Y,where M is unaccessible, return 3 matrices P, D and B,where the columns of P are some eigenvectors of M (DMD modes),D is diagonal with some eigenvalues of M on the diagonal (DMD eigenvalues)and B is a column matrix (DMD mode amplitudes).If n is specified, at most n modes will be computed. Otherwise the numberof computed modes will be determined from the singular values of Xand *epsilon*.

3.11Convergence error

If the algorithms used by mschur, meigenvector, mqz or msvd fail toconverge before *max-iterations* is reached, a convergence-error issignaled. The convergence-error has an error-norm slot giving an indicationhow far from convergence the algorithm was. A restart named use-result-anywayis available if you wish to continue the computations with the current matricesanyway.

The following example computes the eigen decomposition of a matrix M, and in case of a convergence error, it accepts the result if the error norm is small enough and returns nil otherwise.

  (defun eigen-decomposition (m)
    (handler-bind ((convergence-error
                     (lambda (c)
                       (if (< (error-norm c) *epsilon*)
                           (invoke-restart 'use-result-anyway)
                           (return-from eigen-decomposition nil)))))
      (meigen m)))

4Examples

4.1Compute a number of the Fibonacci sequence

  (asdf:load-system "simple-matrix")
  (use-package :simple-matrix)

  (defun fibonacci (n)
    (let* ((m (matrix 2 2 '(1 1 1 0)))
           (mn (mexpt m n)))
      (aref mn 0 1)))

  (fibonacci 39)

  => 63245986
We get: F(39) = 63245986

4.2System of equations with one exact solution

  2x + 3y = 10
  -x + 5y = 5
  (let ((m (matrix 2 2 '(2 3 -1 5)))
        (y (matrix 2 1 '(10 5))))
    (mat->vec (msolve m y)))

  => #(35/13 20/13)
We get: x = 35/13, y = 20/13

4.3System of equations with an infinite number of solutions

One of the possible solutions will be returned.
  x + y + z = 6
  x - y + 3z = 4
  2x + 4z = 10
  (let ((m (matrix 3 3 '(1 1 1 1 -1 3 2 0 4)))
        (y (matrix 3 1 '(6 4 10))))
    (mat->vec (msolve m y)))

  => #(5 1 0)
We get: x = 5, y = 1, z = 0

4.4System of equations with no exact solution

We find an approximate solution using the method of least squares.
  2x + 3y = 10
  -x + 5y = 5
  3x - 3y = 7
  (let ((m (matrix 3 2 '(2 3 -1 5 3 -3)))
        (y (matrix 3 1 '(10 5 7))))
    (mat->vec (mls m y)))

  => #(3.382899628252789d0 1.4200743494423798d0)
We get: x ≈ 3.383, y ≈ 1.42

./doc/img/no-exact-solution.png

4.5System of inequalities

We find a solution with minimal norm using the method of least squareswith inequality constraints.
  -2x - y ≤ -2
  -x + 2y ≤ -2
  -5x + y ≤ -10
  (let ((a (mi 2))
        (b (matrix 2 1))
        (c (matrix 3 2 '(-2 -1 -1 2 -5 1)))
        (d (matrix 3 1 '(-2 -2 -10))))
    (mat->vec (mlsi a b c d)))

  => #(1.9230769230769238d0 -0.3846153846153848d0)
We get: x ≈ 1.923, y ≈ -0.385

./doc/img/inequalities.png

4.6Roots of a polynomial

We find the roots of the polynomial:
x³ - 4x² - 7x + 10
  (mat->vec (mround (msolve-roots '(10 -7 -4 1))))

  => #(-2.0d0 1.0d0 5.0d0)
We get the roots: x₀ = -2, x₁ = 1, x₂ = 5

4.7Polynomial regression

Using the method of least squares, we find an approximation of the form:
y = c₀ + c₁x + c₂x² + c₃x³ + ... + cₙxⁿ
   X | Y
 ----|----
   2 |  1
   3 |  3
   6 | 17
   7 | 23
  (defun polynomial-regression (degree x-values y-values)
    (let* ((n (length x-values))
           (y (vec->mat y-values))
           (m (matrix n (1+ degree))))
      ;; Fill the rows of the matrix with 1, x, x², ...
      (dotimes (i n)
        (dotimes (j (1+ degree))
          (setf (aref m i j) (expt (aref x-values i) j))))
      (mat->vec (mls m y))))

  (let ((x-values #(2 3 6 7))
        (y-values #(1 3 17 23)))
    (polynomial-regression 2 x-values y-values))

  => #(-1.1176470588235325d0 -0.029411764705879667d0 0.49999999999999967d0)
We get the approximation:
y ≈ -1.118 - 0.029x + 0.5x²
./doc/img/polynomial-regression.png

4.8Gaussian regression

Using the method of least squares, we find an approximation of the form:
y = A/(ᵰE * √(2ᵰB)) * exp(-1/2 * ((x - ᵰ7) / ᵰE)²)
Which can be transformed to:
ln(y) = c₀ + c₁x + c₂x²
With:
c₀ = ln(A / (ᵰE * √(2ᵰB))) - ᵰ7² / (2 * ᵰE²)
c₁ = ᵰ7 / ᵰE²
c₂ = -1 / (2 * ᵰE²)

ᵰE = 1 / √(-2 * c₂)
ᵰ7 = c₁ * ᵰE²
A = ᵰE * √(2ᵰB) * exp(c₀ + ᵰ7² / (2 * ᵰE²))
       X     |     Y
 ------------|------------
   5.647237  | 2.4841535
   3.8547695 | 1.0068833
   6.5579185 | 0.3458975
   5.8500857 | 1.8678124
   3.769868  | 0.82293093
   7.1886773 | 0.03394338
   6.6337585 | 0.28119978
   4.71034   | 3.758526
   3.8235922 | 1.0181205
   5.5816703 | 2.8982043
  (defun gaussian-regression (x-values y-values)
    (let* ((n (length x-values))
           (y (vec->mat (map 'vector #'log y-values)))
           (m (matrix n 3)))
      (dotimes (i n)
        (dotimes (j 3)
          (setf (aref m i j) (expt (aref x-values i) j))))
      (let* ((x (mls m y))
             (c0 (aref x 0 0))
             (c1 (aref x 1 0))
             (c2 (aref x 2 0))
             (sigma (/ (sqrt (* -2 c2))))
             (mu (* c1 sigma sigma))
             (a (* sigma
                   (sqrt (* 2 pi))
                   (exp (+ c0 (/ (* mu mu) (* 2 sigma sigma)))))))
        (vector a mu sigma))))

  (let ((x-values #(5.647237 3.8547695 6.5579185 5.8500857 3.769868
                    7.1886773 6.6337585 4.71034 3.8235922 5.5816703))
        (y-values #(2.4841535 1.0068833 0.3458975 1.8678124 0.82293093
                    0.03394338 0.28119978 3.758526 1.0181205 2.8982043)))
    (gaussian-regression x-values y-values))

  => #(6.934017483512708d0 5.005451177669433d0 0.7077270060667742d0)
We get:
A ≈ 6.934
ᵰ7 ≈ 5.005
ᵰE ≈ 0.708
Which gives the approximation:
y ≈ 3.909 * exp(-0.998 * (x - 5.005)²)
./doc/img/gaussian-regression.png

4.9Markov chain

We find the stationary distribution of a system with 3 states, whose transitionmatrix is:
⎛ 90/100  5/100   5/100 ⎞
⎜ 70/100    0    30/100 ⎟
⎝ 80/100    0    20/100 ⎠

./doc/img/markov-chain.png

  (defun markov-stationary (transition-matrix)
    (let* ((n (array-dimension transition-matrix 0))
           (m (m- transition-matrix (mi n)))
           (y (matrix 1 n)))
      ;; Replace a column of M and Y to indicate that x₀ + x₁ + ... + xₙ = 1
      (setf (aref y 0 0) 1)
      (dotimes (i n)
        (setf (aref m i 0) 1))
      (mat->vec (msolve (mt m) (mt y)))))

  (let ((m (matrix 3 3 '(90/100 5/100 5/100
                         70/100 0 30/100
                         80/100 0 20/100))))
    (markov-stationary m))

  => #(160/181 8/181 13/181)
We get:
  • probability to be in the first state: 160/181 ≈ 0.884
  • probability to be in the second state: 8/181 ≈ 0.044
  • probability to be in the third state: 13/181 ≈ 0.072

4.10System of differential equations

  df(x)/dx = f(x) - 2g(x) + 3
  dg(x)/dx = 3f(x) - 4g(x) - 2

  f(0) = 11
  g(0) = 19/2
  (let ((m (matrix 2 2 '(1 -2 3 -4)))
        (v (matrix 2 1 '(11 19/2)))
        (w (matrix 2 1 '(3 -2)))
        (x 3))
    (mat->vec (mround (msolve-ode m v w x))))

  => #(8.054745d0 5.557223d0)
We get: f(3) ≈ 8.055, g(3) ≈ 5.557

./doc/img/differential-equations.png

4.11Discrete Fourier transform

We find the DFT of the 3 Hz signal:

./doc/img/signal.png

  time | signal
 ----------------
   0.1 | -0.309
   0.2 | -0.809
   0.3 |  0.809
   0.4 |  0.309
   0.5 | -1.000
   0.6 |  0.309
   0.7 |  0.809
   0.8 | -0.809
   0.9 | -0.309
   1.0 |  1.000
  (defun dft-matrix (n)
    (let ((m (matrix n 1)))
      (dotimes (k n)
        (setf (aref m k 0) (cis (* -2 pi (/ k n)))))
      (mc/ (mvandermonde m n) (sqrt n))))

  (let* ((signal #(-0.309 -0.809 0.809 0.309 -1 0.309 0.809 -0.809 -0.309 1))
         (n (length signal))
         (x (matrix n 1 signal))
         (dft (dft-matrix n))
         (y (m* dft x))
         (idft (mconj dft))
         (z (m* idft y)))
    (values (m= x z)
            (mat->vec (mround y 1.0d-3))))

  => T
     #(0.0d0 0.0d0 0.0d0 #C(-0.489d0 1.504d0) 0.0d0
       0.0d0 0.0d0 #C(-0.489d0 -1.504d0) 0.0d0 0.0d0)
We get the DFT amplitude:

./doc/img/dft-amplitude.png

4.12Linear-quadratic regulator

We find the optimal control gain matrix for a linear-quadratic regulator fora linear dynamic system defined by:
dx(t)/dt = Ax(t) + Bu(t)
y(t) = x(t)
u(t) = -Kx(t)

A = ⎛  0   1 ⎞   B = ⎛ 0 ⎞   Q = ⎛ 1 0 ⎞   R = ( 1 )
    ⎝ -2  -3 ⎠       ⎝ 1 ⎠       ⎝ 0 0 ⎠

./doc/img/linear-dynamic-system.png

  (defun lqr (a b q r)
    (let* ((tb (mt b))
           (invr (minv r))
           (p (msolve-riccati a (m* b invr tb) q)))
      (m* invr tb p)))

  (let ((a (matrix 2 2 '(0 1 -2 -3)))
        (b (matrix 2 1 '(0 1)))
        (q (matrix 2 2 '(1 0 0 0)))
        (r (matrix 1 1 '(1))))
    (mround (lqr a b q r)))

  => #2A((0.236068d0 0.077684d0))
We get: K ≈ ( 0.236 0.078 )

5Tests

The tests require the fiveam package.They can be run with:
(asdf:test-system "simple-matrix")

Dependencies (1)

  • fiveam

Dependents (0)

    • GitHub
    • Quicklisp