QMatrix

Overview

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

import { QMatrix } from "@masabando/quantum-gates"

Constructor

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],
])

Matrix size

The number of rows and columns can be accessed via getters.

console.log(m1.rows)
console.log(m1.cols)

Addition

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)

Multiplication

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)

Scaling

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))

Conjugate, transpose, and dagger

These methods return new matrices and do not mutate the original instance.

  • conjugate(): element-wise complex conjugation
  • transpose(): matrix transpose
  • dagger(): conjugate transpose
const c = m2.conjugate()
const t = m2.transpose()
const d = m2.dagger()

Trace

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())

String representation

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))

Notes

  • All operations return new QMatrix instances; the original matrix is never modified.
  • QMatrix intentionally avoids advanced optimizations and validation, keeping the implementation simple and readable.