The matrix namespace provides operations for creating and manipulating two-dimensional matrices. Matrices store elements of the same type in rows and columns, supporting operations ranging from basic element access to advanced linear algebra transformations like eigenvalue decomposition and matrix inversion.

Quick Example

from pynecore.lib import matrix, script

@script.indicator(title="Matrix Analysis", overlay=False)
def main():
    # Create a 3x3 matrix
    m = matrix.new(3, 3, 0.0)
    
    # Set diagonal values
    matrix.set(m, 0, 0, 10.0)
    matrix.set(m, 1, 1, 20.0)
    matrix.set(m, 2, 2, 30.0)
    
    # Analyze matrix properties
    is_diag: bool = matrix.is_diagonal(m)
    trace_val: float = matrix.trace(m)  # Sum of diagonal
    avg_val: float = matrix.avg(m)

Matrix Creation and Management

new()

Create a new matrix object.

ParameterTypeDescription
rowsintInitial number of rows (default: 0)
columnsintInitial number of columns (default: 0)
initial_valuefloat | int | str | boolInitial value for all elements (default: NA)

Returns: New matrix object

m = matrix.new(3, 4, 0.0)  # 3×4 matrix filled with 0.0

copy()

Create a copy of an existing matrix with independent row storage.

ParameterTypeDescription
idmatrixMatrix to copy

Returns: New matrix object. Reference-type elements such as drawings and user-defined objects remain shared with the original matrix.

m2 = matrix.copy(m1)  # independent matrix storage, shared reference-type elements

delete()

Delete a matrix object.

ParameterTypeDescription
idmatrixMatrix to delete

Returns: None

The matrix is removed from the list that matrix.all returns. Existing references to it stay usable. Deleting an na matrix, or one already deleted, does nothing.

matrix.delete(m)

all

All matrix objects created with matrix.new() and not deleted, in creation order. Read it bare; it takes no arguments.

Type: list[matrix]

count: int = len(matrix.all)

Dimensions and Properties

rows()

Get the number of rows in a matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: int

row_count: int = matrix.rows(m)  # 3

columns()

Get the number of columns in a matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: int

col_count: int = matrix.columns(m)  # 4

elements_count()

Get the total number of elements in a matrix (rows × columns).

ParameterTypeDescription
idmatrixMatrix object

Returns: int

total: int = matrix.elements_count(m)  # 12

Element Access and Modification

get()

Retrieve an element at a specific row and column.

ParameterTypeDescription
idmatrixMatrix object
rowintRow index (zero-based); a float is truncated to an integer
columnintColumn index (zero-based); a float is truncated to an integer

Returns: Element value, or element-typed na if either index is na.

val: float = matrix.get(m, 0, 1)  # 15.5

set()

Set an element at a specific row and column.

ParameterTypeDescription
idmatrixMatrix object
rowintRow index; a float is truncated to an integer
columnintColumn index; a float is truncated to an integer
valueelement typeValue to assign

Returns: None

If either index is na, the operation is a no-op.

matrix.set(m, 2, 3, 42.0)

fill()

Fill a rectangular area of a matrix with a single value.

ParameterTypeDescription
idmatrixMatrix object
valueelement typeValue to fill with
from_rowintStarting row, inclusive (default: 0)
to_rowintEnding row, exclusive (default: last row)
from_columnintStarting column, inclusive (default: 0)
to_columnintEnding column, exclusive (default: last column)

Returns: None

matrix.fill(m, 0.0, 1, 3, 0, 2)  # Fill rows 1–2, columns 0–1

Row and Column Operations

row()

Extract a row as a one-dimensional array.

ParameterTypeDescription
idmatrixMatrix object
rowintRow index; a float is truncated to an integer

Returns: list — Array of row values, or an na array when row is na.

row_vals: list = matrix.row(m, 1)

col()

Extract a column as a one-dimensional array.

ParameterTypeDescription
idmatrixMatrix object
columnintColumn index; a float is truncated to an integer

Returns: list — Array of column values, or an na array when column is na.

col_vals: list = matrix.col(m, 2)

add_row()

Insert a new row at a specified index.

ParameterTypeDescription
idmatrixMatrix object
rowint | NoneRow index (None appends to end)
array_idlist | NoneArray of values for the new row

Returns: None

matrix.add_row(m, 1, [1.0, 2.0, 3.0, 4.0])

add_col()

Insert a new column at a specified index.

ParameterTypeDescription
idmatrixMatrix object
columnint | NoneColumn index (None appends to end)
array_idlist | NoneArray of values for the new column

Returns: None

matrix.add_col(m, 0, [5.0, 6.0, 7.0])

remove_row()

Remove a row and return its values as an array.

ParameterTypeDescription
idmatrixMatrix object
rowintRow index to remove

Returns: list — Removed row values

removed: list = matrix.remove_row(m, 1)

remove_col()

Remove a column and return its values as an array.

ParameterTypeDescription
idmatrixMatrix object
columnintColumn index to remove

Returns: list — Removed column values

removed: list = matrix.remove_col(m, 2)

swap_rows()

Exchange two rows in a matrix.

ParameterTypeDescription
idmatrixMatrix object
row1intFirst row index
row2intSecond row index

Returns: None

matrix.swap_rows(m, 0, 2)

swap_columns()

Exchange two columns in a matrix.

ParameterTypeDescription
idmatrixMatrix object
column1intFirst column index
column2intSecond column index

Returns: None

matrix.swap_columns(m, 1, 3)

Matrix Property Tests

is_square()

Check if a matrix has equal rows and columns.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_sq: bool = matrix.is_square(m)  # True

is_diagonal()

Check if all elements outside the main diagonal are zero.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_diag: bool = matrix.is_diagonal(m)  # True

is_antidiagonal()

Check if all elements outside the secondary diagonal are zero.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_antidiag: bool = matrix.is_antidiagonal(m)  # False

is_identity()

Check if the matrix is an identity matrix (ones on main diagonal, zeros elsewhere).

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_id: bool = matrix.is_identity(m)  # False

is_symmetric()

Check if a matrix equals its own transpose.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_sym: bool = matrix.is_symmetric(m)  # True

is_antisymmetric()

Check if a matrix equals the negative of its transpose.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_antisym: bool = matrix.is_antisymmetric(m)  # False

is_binary()

Check if all elements are either 0 or 1.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_bin: bool = matrix.is_binary(m)  # False

is_triangular()

Check if all elements above or below the main diagonal are zero.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_tri: bool = matrix.is_triangular(m)  # True

is_stochastic()

Check if the matrix is stochastic (rows or columns sum to 1).

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_stoch: bool = matrix.is_stochastic(m)  # False

is_zero()

Check if all elements are zero.

ParameterTypeDescription
idmatrixMatrix object

Returns: bool

is_z: bool = matrix.is_zero(m)  # False

Arithmetic Operations

sum()

Add two matrices or a matrix and a scalar.

ParameterTypeDescription
id1matrixFirst matrix
id2matrix | float | intSecond matrix or scalar

Returns: New matrix

m3 = matrix.sum(m1, m2)    # Element-wise addition
m4 = matrix.sum(m1, 5.0)   # Add 5.0 to all elements

diff()

Subtract two matrices or a scalar from a matrix.

ParameterTypeDescription
id1matrixMatrix to subtract from
id2matrix | float | intMatrix or scalar to subtract

Returns: New matrix

m3 = matrix.diff(m1, m2)   # Element-wise subtraction
m4 = matrix.diff(m1, 3.0)  # Subtract 3.0 from all elements

mult()

Multiply two matrices or a matrix by a scalar.

ParameterTypeDescription
id1matrixFirst matrix
id2matrix | float | intSecond matrix or scalar

Returns: New matrix

m3 = matrix.mult(m1, m2)   # Matrix multiplication
m4 = matrix.mult(m1, 2.5)  # Scalar multiplication

pow()

Raise a square matrix to a power (multiply by itself n times).

ParameterTypeDescription
idmatrixSquare matrix
powerintExponent

Returns: New matrix

m_squared = matrix.pow(m, 2)  # m × m

Statistical Functions

avg()

Calculate the average of all matrix elements.

ParameterTypeDescription
idmatrixMatrix object

Returns: float \| int

average: float = matrix.avg(m)  # 42.5

min()

Find the smallest element in the matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: float \| int

min_val: float = matrix.min(m)  # 0.0

max()

Find the largest element in the matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: float \| int

max_val: float = matrix.max(m)  # 100.0

median()

Calculate the median of all matrix elements.

ParameterTypeDescription
idmatrixMatrix object

Returns: float \| int

med: float = matrix.median(m)  # 50.0

mode()

Find the most frequently occurring element in the matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: Most frequent value (or smallest if no unique mode)

most_common: float = matrix.mode(m)  # 25.0

Linear Algebra

transpose()

Create a new matrix with rows and columns swapped.

ParameterTypeDescription
idmatrixMatrix object

Returns: New matrix

m_t = matrix.transpose(m)

det()

Calculate the determinant of a square matrix.

ParameterTypeDescription
idmatrixSquare matrix

Returns: float \| int

determinant: float = matrix.det(m)  # -2.0

inv()

Calculate the inverse of a square matrix.

ParameterTypeDescription
idmatrixSquare matrix

Returns: New matrix — The inverse, solved from the LU decomposition with partial pivoting.

A singular matrix is a runtime error, and so is one whose LU decomposition meets a pivot smaller than 1e-11 in magnitude.

m_inv = matrix.inv(m)

pinv()

Calculate the pseudo-inverse (Moore-Penrose inverse) of a matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: New matrix of columns × rows cells — The pseudoinverse. A square matrix that inv() can invert returns its inverse, and a matrix with fewer rows than columns returns Aᵀ(AAᵀ)⁻¹ while AAᵀ can be inverted. Every other matrix, including a singular or otherwise rank-deficient one, returns the pseudoinverse of its singular value decomposition, in which a singular value up to max(rows, columns) × s_max × 2⁻⁵² counts as zero.

m = matrix.new(2, 2, 1.0)
matrix.set(m, 0, 1, 2.0)
matrix.set(m, 1, 0, 2.0)
matrix.set(m, 1, 1, 4.0)
m_pinv = matrix.pinv(m)  # [[0.04, 0.08], [0.08, 0.16]]

rank()

Calculate the rank of a matrix.

ParameterTypeDescription
idmatrixMatrix object

Returns: int

r: int = matrix.rank(m)  # 2

trace()

Calculate the trace (sum of main diagonal elements).

ParameterTypeDescription
idmatrixSquare matrix

Returns: float \| int

tr: float = matrix.trace(m)  # 30.0

eigenvalues()

Calculate the eigenvalues of a square matrix.

ParameterTypeDescription
idmatrixSquare int or float matrix without na elements

Returns: list — Array of eigenvalues, with the element type of the matrix: an int matrix gives an int array that still holds the fractional eigenvalues. A symmetric matrix returns them in descending order. Any other matrix returns them in the order they take on the diagonal of its real Schur form, which is not sorted. A complex conjugate pair a ± bi contributes its real part a twice.

An empty matrix, a matrix with an na element and a non-square matrix are runtime errors.

m = matrix.new(2, 2, 1.0)
matrix.set(m, 0, 0, 2.0)
matrix.set(m, 1, 1, 2.0)
evals: list[float] = matrix.eigenvalues(m)  # [3.0, 1.0000000000000002]

eigenvectors()

Calculate the eigenvectors of a square matrix.

ParameterTypeDescription
idmatrixSquare int or float matrix without na elements

Returns: New matrix of the type of id (an int matrix gives an int matrix that still holds fractional values) — Column i is the eigenvector of the i-th element of eigenvalues(). The eigenvectors of a symmetric matrix are orthonormal. Those of any other matrix are not normalized. The two columns of a complex conjugate pair hold the real and the imaginary part of the complex eigenvector of the eigenvalue with the positive imaginary part; its conjugate is the eigenvector of the other eigenvalue of the pair.

The same inputs are runtime errors as for eigenvalues().

evecs = matrix.eigenvectors(m)  # columns [0.7071…, 0.7071…] and [0.7071…, -0.7071…]

Matrix Transformations

submatrix()

Extract a rectangular submatrix.

ParameterTypeDescription
idmatrixMatrix object
from_rowintStarting row (inclusive)
to_rowintEnding row (exclusive)
from_columnintStarting column (inclusive)
to_columnintEnding column (exclusive)

Returns: New matrix

sub = matrix.submatrix(m, 1, 3, 0, 2)  # Rows 1–2, columns 0–1

reshape()

Reorganize the matrix to new dimensions (preserves all elements).

ParameterTypeDescription
idmatrixMatrix object
rowsintNew number of rows
columnsintNew number of columns

Returns: None — Modifies in place

matrix.reshape(m, 4, 3)  # Reorganize to 4×3

reverse()

Reverse the order of rows and columns.

ParameterTypeDescription
idmatrixMatrix object

Returns: None — Modifies in place

matrix.reverse(m)

concat()

Append one matrix to another.

ParameterTypeDescription
id1matrixMatrix to concatenate into
id2matrixMatrix to append

Returns: Modified first matrix

m3 = matrix.concat(m1, m2)

sort()

Sort rows based on values in a specific column.

ParameterTypeDescription
idmatrixMatrix object
columnintColumn index to sort by
orderstr"ascending" or "descending"

Returns: None — Modifies in place

matrix.sort(m, 2, "ascending")

kron()

Calculate the Kronecker product of two matrices.

ParameterTypeDescription
id1matrixFirst matrix
id2matrixSecond matrix

Returns: New matrix

m_kron = matrix.kron(m1, m2)

Compatibility Notes

  • All matrix elements must be the same type
  • Matrix indices are zero-based
  • Float-valued dimensions, indices, and powers are truncated to integers before use
  • NA (not available) values are handled automatically; operations on an NA matrix return NA or do nothing, depending on whether the operation returns a value or mutates the matrix
  • Linear algebra functions (inv, eigenvalues, etc.) require square or compatible matrices
  • eigenvalues() and eigenvectors() give TradingView’s results to the last bit, including the order of the eigenvalues and the scale and sign of the eigenvectors
  • inv() and pinv() give TradingView’s results to the last bit
  • For very large matrices, performance depends on matrix size and operation complexity