Sidechair

matrix.inv()

Browse the reference

Returns the inverse of a square matrix, the matrix that multiplies with it to give the identity.

Try it in the editor

Only a square matrix with a non-zero determinant has an inverse. Check matrix.det() first, or use matrix.pinv() when the matrix may be singular or is not square.

For [[a, b], [c, d]] with determinant D the inverse is [[d, -b], [-c, a]] divided by D, so [[2, 0], [0, 4]] inverts to [[0.5, 0], [0, 0.25]]. Multiplying a matrix by its inverse, in either order, gives the identity matrix up to rounding.

Syntax

Pine Script
matrix.inv(id: matrix<int/float>) -> matrix<float>
matrix.inv(id: matrix<int>) -> matrix<int>
matrix.inv() -> matrix<float>
matrix.inv() -> matrix<int>

Arguments

NameTypeDefaultDescription
idmatrix<int/float> or matrix<int>requiredThe square matrix to invert; its determinant must not be 0 or no inverse exists.

Returns

  • matrix<float>: A new float matrix with the inverse, the same size as id.
  • matrix<int>: A new matrix typed as integers; an inverse with decimals needs a decimal-valued matrix to keep them.
  • matrix<float>: A new float matrix with the inverse of the receiving matrix.
  • matrix<int>: A new matrix typed as integers, holding the inverse of the receiving matrix.

Remarks

  • On Sidechair: a matrix with no inverse gives a matrix of na.

Example

Pine ScriptSolve a small systemOpen in editor
//@version=6
indicator("matrix.inv: solve", overlay = false)
matrix<float> a = matrix.new<float>(2, 2, 0.0)
matrix.set(a, 0, 0, 2.0)
matrix.set(a, 1, 1, 4.0)
x = matrix.mult(matrix.inv(a), array.from(6.0, 8.0))
plot(array.get(x, 0), "First unknown")

See also

Runs on Sidechair