matrix

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 an independent copy of an existing matrix.

ParameterTypeDescription
idmatrixMatrix to copy

Returns: New matrix object

m2 = matrix.copy(m1)  # m2 is independent from m1

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)
columnintColumn index (zero-based)

Returns: Element value

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

set()

Set an element at a specific row and column.

ParameterTypeDescription
idmatrixMatrix object
rowintRow index
columnintColumn index
valueelement typeValue to assign

Returns: None

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

Returns: list — Array of row values

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

col()

Extract a column as a one-dimensional array.

ParameterTypeDescription
idmatrixMatrix object
columnintColumn index

Returns: list — Array of column values

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

m_inv = matrix.inv(m)

pinv()

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

ParameterTypeDescription
idmatrixMatrix object

Returns: New matrix

m_pinv = matrix.pinv(m)

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 matrix

Returns: list — Array of eigenvalues

evals: list = matrix.eigenvalues(m)

eigenvectors()

Calculate the eigenvectors of a square matrix.

ParameterTypeDescription
idmatrixSquare matrix

Returns: New matrix — Each column is an eigenvector

evecs = matrix.eigenvectors(m)

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
  • NA (not available) values are handled automatically—operations on NA return NA
  • Linear algebra functions (inv, eigenvalues, etc.) require square or compatible matrices
  • For very large matrices, performance depends on matrix size and operation complexity