trekhleb/javascript-algorithms · error · Error
Matrices have different dimensions
Error message
Matrices have different dimensions
What it means
Thrown by validateSameShape() in src/algorithms/math/matrix/Matrix.js:69 when the matrices passed to the element-wise operations add(), mul() or sub() have a different number of dimensions (rank). The library derives each matrix shape (e.g. [2,3] for 2 rows x 3 columns) and rejects the operation when the two shape arrays differ in length, because element-wise math is undefined across different nesting depths. Example: add([[1,2]], [[[1,2]]]) compares shape [1,2] against [1,1,2] and fails here. This is the rank check; per-axis size mismatches raise the separate 'Matrices have different shapes' error.
Source
Thrown at src/algorithms/math/matrix/Matrix.js:69
}
};
/**
* Validates that matrices are of the same shape.
*
* @param {Matrix} a
* @param {Matrix} b
* @trows {Error}
*/
export const validateSameShape = (a, b) => {
validateType(a);
validateType(b);
const aShape = shape(a);
const bShape = shape(b);
if (aShape.length !== bShape.length) {
throw new Error('Matrices have different dimensions');
}
while (aShape.length && bShape.length) {
if (aShape.pop() !== bShape.pop()) {
throw new Error('Matrices have different shapes');
}
}
};
/**
* Generates the matrix of specific shape with specific values.
*
* @param {Shape} mShape - the shape of the matrix to generate
* @param {function({CellIndex}): Cell} fill - cell values of a generated matrix.
* @returns {Matrix}
*/
export const generate = (mShape, fill) => {
/**View on GitHub (pinned to 85293e3e2b)
Solutions
- Print both shapes with the exported shape() helper (shape(a) vs shape(b)) to find which argument has the extra or missing nesting level
- Fix the data: wrap the flat array ([1,2] becomes [[1,2]]) or flatten the deeper one so both matrices have the same rank
- If you actually want matrix multiplication, call dot(a, b) instead of mul(a, b)
- If per-axis sizes must be reconciled, pad or slice with zeros() until shapes match before calling add/mul/sub
Example fix
// before
import { add } from './src/algorithms/math/matrix/Matrix';
const result = add([[1, 2], [3, 4]], [1, 2]);
// throws: shapes [2,2] vs [2]
// after
const result = add([[1, 2], [3, 4]], [[1, 2], [1, 2]]);
// both shapes are [2,2] Defensive patterns
Strategy: validation
Validate before calling
import { shape } from './src/algorithms/math/matrix/Matrix';
const sameRank = (a, b) => shape(a).length === shape(b).length;
if (!sameRank(matrixA, matrixB)) {
throw new TypeError('rank mismatch: ' + JSON.stringify(shape(matrixA)) + ' vs ' + JSON.stringify(shape(matrixB)));
}
const sum = add(matrixA, matrixB); Type guard
import { shape } from './src/algorithms/math/matrix/Matrix';
const isMatrixOfRank = (m, rank) => Array.isArray(m) && shape(m).length === rank;
// usage: isMatrixOfRank(a, 2) && isMatrixOfRank(b, 2) Try / catch
try {
result = add(a, b);
} catch (e) {
if (e.message === 'Matrices have different dimensions') {
throw new Error('add(): rank mismatch ' + JSON.stringify(shape(a)) + ' vs ' + JSON.stringify(shape(b)), { cause: e });
}
throw e;
} Prevention
- Log shape(a) and shape(b) next to every add/mul/sub call during development
- Normalize inputs to a fixed rank (e.g. always 2D) right after loading data
- Share one assertSameShape helper across unit tests
When it happens
Trigger: Calling add(a, b), mul(a, b) or sub(a, b) where one argument is 2D ([[1,2],[3,4]]) and the other is 3D ([[[1,2]]]), or a flat row [1,2] is passed where a matrix [[1,2]] is expected (shape [2] vs [2,2]).
Common situations: Mixing data sources with different nesting conventions (flat points array vs grid), refactors that add or remove a nesting level, JSON round-trips that collapse single-element arrays, or passing a vector where the API expects a matrix.
Related errors
- Matrices have different shapes
- Matrices have incompatible shape for multiplication
- The method supports only positive integers
AI-assisted analysis of trekhleb/javascript-algorithms@85293e3e2b (2026-08-24).
Data as JSON: /api/errors/b7509e0b7e8d0501.
Report an issue: GitHub.