Sidechair

matrix.pinv()

Browse the reference

Returns the pseudoinverse of a matrix of any shape, the closest thing to an inverse when none exists.

Try it in the editor

It is the Moore-Penrose pseudoinverse. For an invertible square matrix it equals matrix.inv(); for a tall matrix of observations it gives the least-squares solution when multiplied by the target vector.

The result has the shape of the transpose: an m by n input gives an n by m output. A column of three ones, [[1], [1], [1]], has the pseudoinverse [[1/3, 1/3, 1/3]], the row that averages three numbers.

Use it for regressions on more equations than unknowns, or when a matrix may be singular.

Syntax

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

Arguments

NameTypeDefaultDescription
idmatrix<int/float> or matrix<int>requiredThe matrix to pseudo-invert, of any shape; the result has its row and column counts swapped.

Returns

  • matrix<float>: A new float matrix with the pseudoinverse, sized columns by rows of id.
  • matrix<int>: A new matrix typed as integers, sized columns by rows of id.
  • matrix<float>: A new float matrix with the pseudoinverse of the receiving matrix.
  • matrix<int>: A new matrix typed as integers, holding the pseudoinverse of the receiving matrix.

Example

Pine ScriptLeast squares lineOpen in editor
//@version=6
indicator("matrix.pinv: least squares", overlay = false)
matrix<float> x = matrix.new<float>(0, 2)
matrix.add_row(x, 0, array.from(1.0, 1.0))
matrix.add_row(x, 1, array.from(1.0, 2.0))
matrix.add_row(x, 2, array.from(1.0, 3.0))
beta = matrix.mult(matrix.pinv(x), array.from(2.0, 4.1, 5.9))
plot(array.get(beta, 1), "Slope")

See also

Runs on Sidechair