QMatrix is a minimal utility class for handling small complex matrices. It is primarily used as an internal representation for quantum gates and constants, and focuses on clarity rather than performance optimizations.
import { QMatrix } from "@masabando/quantum-gates"A QMatrix is constructed from a two-dimensional array of numbers orComplex values. Numeric entries are automatically converted into complex numbers with zero imaginary part.
import { QMatrix, Complex } from "@masabando/quantum-gates"const m1 = new QMatrix([ [1, 0], [0, 1],])const m2 = new QMatrix([ [new Complex(0, 1), 0], [0, 1],])The number of rows and columns can be accessed via getters.
console.log(m1.rows)console.log(m1.cols)add performs element-wise addition of two matrices with the same shape. If the dimensions do not match, an error is thrown.
const sum = m1.add(m2)multiply computes the matrix product. The number of columns of the left matrix must match the number of rows of the right matrix.
const prod = m1.multiply(m2)scale multiplies every element by a scalar value. The scalar can be either a number or a Complex instance.
const half = m1.scale(0.5)const phase = m1.scale(new Complex(0, 1))These methods return new matrices and do not mutate the original instance.
conjugate(): element-wise complex conjugationtranspose(): matrix transposedagger(): conjugate transposeconst c = m2.conjugate()const t = m2.transpose()const d = m2.dagger()trace returns the sum of diagonal elements. For non-square matrices, the sum is taken up to min(rows, cols).
const tr = m2.trace()console.log(tr.toString())toString formats the matrix as a tab-separated grid. An optional argument controls the number of displayed digits.
console.log(m2.toString())console.log(m2.toString(4))QMatrix instances; the original matrix is never modified.QMatrix intentionally avoids advanced optimizations and validation, keeping the implementation simple and readable.