Core concept

A matrix is a class instance with row-major Float64Array storage. AbstractMatrix is the abstract base that implements everything in terms of the get / set / rows / columns contract; Matrix is the concrete dense implementation. Views, wrappers, SymmetricMatrix, and DistanceMatrix are other AbstractMatrix subclasses.

import { Matrix } from "@teakit/matrix";

const a = new Matrix([
  [1, 2],
  [3, 4],
]);
a.rows; // 2
a.columns; // 2
a.size; // 4
a.get(0, 1); // 2
a.set(0, 1, 9); // mutates, returns `this`

Construction

new Matrix(rows, columns); // zero-filled
new Matrix([[1, 2], [3, 4]]); // from a 2D array (copied)
new Matrix(otherMatrix); // copy

Matrix.zeros(2, 3);
Matrix.ones(2, 3);
Matrix.eye(3); // identity (alias: Matrix.identity)
Matrix.diag([1, 2, 3]); // diagonal (alias: Matrix.diagonal)
Matrix.rand(2, 2); // alias: Matrix.random
Matrix.randInt(2, 2, { min: 0, max: 10 }); // alias: Matrix.randomInt
Matrix.from1DArray(2, 2, [1, 2, 3, 4]);
Matrix.rowVector([1, 2, 3]); // 1×3
Matrix.columnVector([1, 2, 3]); // 3×1

new Matrix(...) does not accept a 1D array — use rowVector, columnVector, or from1DArray.

Validation

Matrix.isMatrix(value); // value is AbstractMatrix
Matrix.checkMatrix(value); // returns a Matrix, wrapping a 2D array if needed

Mutation model

  • Instance methods mutate this and return it for chaining: m.add(2).mul(3).
  • Static methods return a new matrix: Matrix.add(a, 2) leaves a untouched.
  • clone() makes an independent copy.

Conversion and inspection

m.to1DArray(); // number[] (row by row)
m.to2DArray(); // number[][]
m.toJSON(); // number[][]
m.toString({ maxRows: 15, maxColumns: 10 });
for (const [row, col, value] of m) {
  /* entries(); also m.values() */
}

Shape queries

isRowVector, isColumnVector, isVector, isSquare, isSymmetric, isEmpty, isDistance, isEchelonForm, isReducedEchelonForm.