On this page:
matrix-solve
matrix-inverse
matrix-invertible?
matrix-determinant

7.9 Solving Systems of Equations

procedure

(matrix-solve M B [fail])  (U F (Matrix Number))

  M : (Matrix Number)
  B : (Matrix Number)
  fail : (-> F) = (λ () (error ...))
Returns the matrix X for which (matrix* M X) is B. M and B must have the same number of rows.

It is typical for B (and thus X) to be a column matrix, but not required. If B is not a column matrix, matrix-solve solves for all the columns in B simultaneously.

Examples:
> (define M (matrix [[7 5] [3 -2]]))
> (define B0 (col-matrix [3 22]))
> (define B1 (col-matrix [19 4]))
> (matrix-solve M B0)

- : (Array Real)

(array #[#[4] #[-5]])

> (matrix* M (col-matrix [4 -5]))

- : (Array Integer)

(array #[#[3] #[22]])

> (matrix-solve M B1)

- : (Array Real)

(array #[#[2] #[1]])

> (matrix-cols (matrix-solve M (matrix-augment (list B0 B1))))

- : (Listof (Array Real))

(list (array #[#[4] #[-5]]) (array #[#[2] #[1]]))

matrix-solve does not solve overconstrained or underconstrained systems, meaning that M must be invertible. If M is not invertible, the result of applying the failure thunk fail is returned.

matrix-solve is implemented using matrix-gauss-elim to preserve exactness in its output, with partial pivoting for greater numerical stability when M is not exact.

See vandermonde-matrix for an example that uses matrix-solve to compute Legendre polynomials.

procedure

(matrix-inverse M [fail])  (U F (Matrix Number))

  M : (Matrix Number)
  fail : (-> F) = (λ () (error ...))
Wikipedia: Invertible Matrix Returns the inverse of M if it exists; otherwise returns the result of applying the failure thunk fail.

Examples:
> (matrix-inverse (identity-matrix 3))

- : (Array Real)

(array #[#[1 0 0] #[0 1 0] #[0 0 1]])

> (matrix-inverse (matrix [[7 5] [3 -2]]))

- : (Array Real)

(array #[#[2/29 5/29] #[3/29 -7/29]])

> (matrix-inverse (matrix [[1 2] [10 20]]))

matrix-inverse: contract violation

  expected: matrix-invertible?

  given: (array #[#[1 2] #[10 20]])

> (matrix-inverse (matrix [[1 2] [10 20]]) (λ () #f))

- : (U (Array Real) False)

#f

procedure

(matrix-invertible? M)  Boolean

  M : (Matrix Number)
Returns #t when M is a square-matrix? and (matrix-determinant M) is nonzero.

procedure

(matrix-determinant M)  Number

  M : (Matrix Number)
Wikipedia: Determinant Returns the determinant of M, which must be a square-matrix?.

Examples:
> (matrix-determinant (diagonal-matrix '(1 2 3 4)))

- : Real

24

> (* 1 2 3 4)

- : Integer [more precisely: Positive-Integer]

24

> (matrix-determinant (matrix [[1 2] [10 20]]))

- : Real

0

> (matrix-determinant (col-matrix [1 2]))

square-matrix-size: contract violation

  expected: square-matrix?

  given: (array #[#[1] #[2]])