Special matrices

Both extend AbstractMatrix, so all the usual operations work on them.

SymmetricMatrix

A square matrix whose set mirrors across the diagonal, with a compact storage format.

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

const s = new SymmetricMatrix(3); // 3×3, zero-filled
new SymmetricMatrix(existingMatrix); // throws TypeError if not symmetric
new SymmetricMatrix([[1, 2], [2, 1]]); // throws if data is not symmetric

s.set(0, 1, 5); // also sets (1, 0)
s.diagonalSize; // alias for rows/columns

SymmetricMatrix.isSymmetricMatrix(value); // instance check (value is SymmetricMatrix)
SymmetricMatrix.zeros(n);
SymmetricMatrix.ones(n);

s.toMatrix(); // copy to a plain Matrix
s.clone();

// Symmetric structural edits (keep symmetry):
s.removeCross(index); // remove row + column index
s.addCross(index, array); // add a symmetric row/column
s.applyMask([1, 0, 1]); // drop sides where the mask is falsy

// Compact upper-right representation:
s.toCompact(); // number[]
SymmetricMatrix.fromCompact(compact);
for (const [row, col, value] of s.upperRightEntries()) {
  /* also s.upperRightValues() */
}

DistanceMatrix

A SymmetricMatrix whose diagonal is forced to 0.

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

const d = new DistanceMatrix(4); // throws if the data is not a valid distance matrix
d.set(0, 0, 5); // diagonal stays 0
DistanceMatrix.isDistanceMatrix(value);
d.toSymmetricMatrix();
d.toCompact(); // number[] (no diagonal)
DistanceMatrix.fromCompact(compact);