trekhleb/javascript-algorithms · error · Error

Matrices have different shapes

Error message

Matrices have different shapes

What it means

Thrown by validateSameShape() in src/algorithms/math/matrix/Matrix.js:74 when two matrices passed to add(), mul() or sub() have the same number of dimensions but differ in size along at least one axis. The validator pops sizes off both shape arrays and compares them axis by axis, so [[1,2],[3,4]] (shape [2,2]) plus [[1,2,3],[4,5,6]] (shape [2,3]) fails on the second axis. Element-wise operations are only defined for identically shaped inputs, so the library fails fast instead of producing undefined cells.

Source

Thrown at src/algorithms/math/matrix/Matrix.js:74

 *
 * @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) => {
  /**
   * Generates the matrix recursively.
   *
   * @param {Shape} recShape - the shape of the matrix to generate
   * @param {CellIndices} recIndices
   * @returns {Matrix}

View on GitHub (pinned to 85293e3e2b)

Solutions

  1. Print shape(a) and shape(b) with the exported shape() helper to identify the offending axis
  2. Slice the larger matrix (b.map(row => row.slice(0, a[0].length)) or b.slice(0, a.length)) so both shapes match exactly
  3. Pad the smaller one by building zeros(shape(a)) and copying values in
  4. Fix the mis-sized input at its source rather than patching at the call site

Example fix

// before
import { add } from './src/algorithms/math/matrix/Matrix';
const sum = add([[1, 2], [3, 4]], [[1, 2, 3], [4, 5, 6]]);
// throws: shapes [2,2] vs [2,3]

// after
const trimmed = [[1, 2, 3], [4, 5, 6]].map((row) => row.slice(0, 2));
const sum = add([[1, 2], [3, 4]], trimmed);
// both shapes are [2,2]
Defensive patterns

Strategy: validation

Validate before calling

import { shape } from './src/algorithms/math/matrix/Matrix';

const sameShape = (a, b) => {
  const sa = shape(a);
  const sb = shape(b);
  return sa.length === sb.length && sa.every((dim, i) => dim === sb[i]);
};
if (!sameShape(a, b)) {
  throw new TypeError('shape mismatch: ' + JSON.stringify(shape(a)) + ' vs ' + JSON.stringify(shape(b)));
}
const sum = add(a, b);

Type guard

import { shape } from './src/algorithms/math/matrix/Matrix';

const isSameShapeMatrix = (a, b) => {
  const sa = shape(a);
  const sb = shape(b);
  return Array.isArray(a) && Array.isArray(b) && sa.length === sb.length && sa.every((d, i) => d === sb[i]);
};

Try / catch

try {
  result = sub(a, b);
} catch (e) {
  if (e.message === 'Matrices have different shapes') {
    result = zeros(shape(a)); // or log and skip this batch
  } else {
    throw e;
  }
}

Prevention

When it happens

Trigger: add/mul/sub where row counts differ (2x2 + 2x3), column counts differ, or in higher-rank inputs one batch has more entries than the other along any axis.

Common situations: Ragged rows from CSV/JSON parsing, concatenating matrices then forgetting to trim to equal extent, off-by-one slicing (data.slice(0, n) vs data.slice(0, n - 1)), or a pipeline change that altered one matrix dimension while the other stayed fixed.

Related errors


AI-assisted analysis of trekhleb/javascript-algorithms@85293e3e2b (2026-08-24). Data as JSON: /api/errors/f304ca7d81706e79. Report an issue: GitHub.