data-structure

Exploring Matrix Data Structure in TypeScript

A matrix is a 2D grid of numbers arranged in rows and columns. If you've ever worked with images, game boards, spreadsheets, or machine learning features,...

20 Apr 2024

A matrix is a 2D grid of numbers arranged in rows and columns. If you've ever worked with images, game boards, spreadsheets, or machine learning features, you've worked with matrices.

In TypeScript, a matrix is just an array of arrays.

Typescript
type Matrix = number[][];

const matrix: Matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

Access is straightforward: matrix[row][col]. Row 0, column 2 gives you 3.

Matrix Addition

Add two matrices by summing corresponding elements. Both matrices must have the same dimensions.

Typescript
function addMatrices(a: Matrix, b: Matrix): Matrix {
  return a.map((row, i) =>
    row.map((val, j) => val + b[i][j])
  );
}

Matrix Multiplication

This is where it gets interesting. Multiplying an m×n matrix by an n×p matrix produces an m×p matrix. Each element is the dot product of a row from the first matrix and a column from the second.

Typescript
function multiplyMatrices(a: Matrix, b: Matrix): Matrix {
  const rows = a.length;
  const cols = b[0].length;
  const n = b.length;

  const result: Matrix = Array.from({ length: rows }, () =>
    new Array(cols).fill(0)
  );

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      for (let k = 0; k < n; k++) {
        result[i][j] += a[i][k] * b[k][j];
      }
    }
  }
  return result;
}

Matrix multiplication is O(n³) with the naive approach. Optimized algorithms like Strassen's can do better, but for most practical TypeScript use cases, the naive approach is fine.

Matrix Transposition

Swap rows and columns. The element at position (i, j) moves to (j, i).

Typescript
function transpose(matrix: Matrix): Matrix {
  return matrix[0].map((_, colIdx) =>
    matrix.map(row => row[colIdx])
  );
}

When Matrices Show Up

  • Computer graphics: Every rotation, scale, and translation is a matrix multiplication. GPUs are essentially matrix multiplication machines.
  • Image processing: An image is a matrix of pixel values. Convolution filters (blur, sharpen, edge detect) are matrix operations.
  • Machine learning: Feature datasets are matrices. Training neural networks is fundamentally matrix math.
  • Game development: Game boards, tile maps, and collision grids are all 2D matrices.
  • Physics simulations: Forces, transformations, and state transitions are expressed as matrices.

The Trade-off

Matrices are memory-intensive. An n×n matrix uses O(n²) space. If most elements are zero (sparse matrix), use a specialized representation like coordinate lists or compressed sparse row format instead of a full 2D array.

For dense numerical work in production, consider libraries like mathjs or ndarray rather than rolling your own. For learning and small-scale operations, the plain array-of-arrays approach works perfectly.

Keep reading