Matrix Math for Developers Who Skipped Linear Algebra
Source: Dev.to
Matrices and Basic Operations
Representation
A matrix is simply a 2‑dimensional array of numbers. For example, a 3×3 matrix:
| 1 | 2 | 3 |
|---|---|---|
| 4 | 5 | 6 |
| 7 | 8 | 9 |
In JavaScript it can be created as:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];Element‑wise Addition
Both matrices must have the same dimensions.
function add(A, B) {
return A.map((row, i) => row.map((val, j) => val + B[i][j]));
}Matrix Multiplication
Multiplication is not element‑wise. The element at position (i, j) in the result is the dot product of row i from A and column j from B.
Requirements: the number of columns in A must equal the number of rows in B. An m×n matrix multiplied by an n×p matrix yields an m×p matrix.
function multiply(A, B) {
const rows = A.length;
const cols = B[0].length;
const n = B.length;
const result = Array.from({ length: rows }, () =>
Array(cols).fill(0)
);
for (let i = 0; i
Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))
);
}Transpose
Swaps rows and columns; row i becomes column i.
function transpose(M) {
return M[0].map((_, j) => M.map(row => row[j]));
}Transposition is frequently used in machine‑learning pipelines to switch between “features‑as‑columns” and “features‑as‑rows” layouts.
Determinant
The determinant of a square matrix is a single number indicating invertibility (non‑zero) or singularity (zero).
2×2 determinant:
function det2x2(M) {
return M[0][0] * M[1][1] - M[0][1] * M[1][0];
}General determinant (cofactor expansion):
function determinant(M) {
const n = M.length;
if (n === 1) return M[0][0];
if (n === 2) return det2x2(M);
let det = 0;
for (let j = 0; j
[...row.slice(0, j), ...row.slice(j + 1)]
);
det += M[0][j] * determinant(minor) * (j % 2 === 0 ? 1 : -1);
}
return det;
}Real‑World Applications
CSS Transforms
Every CSS transform (translate, rotate, scale, skew) is internally represented as a matrix operation. The browser builds a 4×4 transformation matrix and applies it to each pixel.
/* CSS declaration */
transform: rotate(45deg) scale(1.5) translate(10px, 20px);
/* Internally computed as a matrix */
transform: matrix(1.06, 1.06, -1.06, 1.06, -11.21, 25.61);3D Graphics
Game engines and 3D renderers use 4×4 matrices for camera positioning, object transformations, and projection from 3D world space to 2D screen space.
Machine Learning
Neural networks are essentially sequences of matrix multiplications (weights) interleaved with nonlinear activation functions. Training adjusts those weight matrices.
Image Processing
Convolution filters (blur, sharpen, edge detection) are applied via small kernels—matrices that are multiplied against local image patches.
Handy Tools
For quick, interactive calculations (multiplication, determinants, inverses, transposes, eigenvalues, etc.), try the free online matrix calculator: