{"record":{"id":"30c765d25d72cbb6","repo":"trekhleb/javascript-algorithms","slug":"matrices-have-incompatible-shape-for-multiplicatio","errorCode":null,"errorMessage":"Matrices have incompatible shape for multiplication","messagePattern":"Matrices have incompatible shape for multiplication","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/algorithms/math/matrix/Matrix.js","lineNumber":135,"sourceCode":"  return generate(mShape, () => 0);\n};\n\n/**\n * @param {Matrix} a\n * @param {Matrix} b\n * @return Matrix\n * @throws {Error}\n */\nexport const dot = (a, b) => {\n  // Validate inputs.\n  validate2D(a);\n  validate2D(b);\n\n  // Check dimensions.\n  const aShape = shape(a);\n  const bShape = shape(b);\n  if (aShape[1] !== bShape[0]) {\n    throw new Error('Matrices have incompatible shape for multiplication');\n  }\n\n  // Perform matrix multiplication.\n  const outputShape = [aShape[0], bShape[1]];\n  const c = zeros(outputShape);\n\n  for (let bCol = 0; bCol < b[0].length; bCol += 1) {\n    for (let aRow = 0; aRow < a.length; aRow += 1) {\n      let cellSum = 0;\n      for (let aCol = 0; aCol < a[aRow].length; aCol += 1) {\n        cellSum += a[aRow][aCol] * b[aCol][bCol];\n      }\n      c[aRow][bCol] = cellSum;\n    }\n  }\n\n  return c;\n};","sourceCodeStart":117,"sourceCodeEnd":153,"githubUrl":"https://github.com/trekhleb/javascript-algorithms/blob/85293e3e2b88f4d2ce330d956b139cf628aa1e82/src/algorithms/math/matrix/Matrix.js#L117-L153","documentation":"Thrown by dot(a, b) in src/algorithms/math/matrix/Matrix.js:135 when the inner dimensions of two 2D matrices do not agree: the number of columns of a (aShape[1]) must equal the number of rows of b (bShape[0]). This is the classic (n x m) * (m x p) rule of matrix multiplication; a 2x3 times a 2x2 fails because 3 !== 2. Both inputs have already passed validate2D() at this point, so the error is purely about inner-dimension alignment, not type or rank.","triggerScenarios":"dot([[1,2,3],[4,5,6]], [[1,2],[3,4]]) (2x3 * 2x2); multiplying a weights matrix by a feature vector shaped as a row when it must be a column; chaining dot(a, b) where b came from a previous dot with a different output width.","commonSituations":"Row-vector vs column-vector orientation confusion, weight matrices from a trained model expecting a different feature count than the input provides, swapped operand order (dot(a, b) vs dot(b, a)), or an upstream schema change that added a feature column.","solutions":["Log shape(a) and shape(b) and confirm which orientation you intended","Transpose the right operand: dot(a, t(b)) using the exported t() when b is oriented wrong","Swap operand order: dot(b, a) is often legal where dot(a, b) is not","If a weights matrix expects a different feature count, fix the feature vector upstream to match"],"exampleFix":"// before\nimport { dot } from './src/algorithms/math/matrix/Matrix';\nconst result = dot([[1, 2, 3], [4, 5, 6]], [[1, 2], [3, 4]]);\n// throws: 2x3 * 2x2, inner dims 3 !== 2\n\n// after\nconst result = dot([[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4]]);\n// ok: 3x2 * 2x2","handlingStrategy":"validation","validationCode":"import { shape, dot } from './src/algorithms/math/matrix/Matrix';\n\nconst canMultiply = (a, b) => shape(a)[1] === shape(b)[0];\nif (!canMultiply(a, b)) {\n  throw new TypeError('cannot multiply ' + JSON.stringify(shape(a)) + ' by ' + JSON.stringify(shape(b)));\n}\nconst product = dot(a, b);","typeGuard":"import { shape } from './src/algorithms/math/matrix/Matrix';\n\nconst isMultipliablePair = (a, b) => {\n  const sa = shape(a);\n  const sb = shape(b);\n  return sa.length === 2 && sb.length === 2 && sa[1] === sb[0];\n};","tryCatchPattern":"import { dot, t } from './src/algorithms/math/matrix/Matrix';\n\ntry {\n  c = dot(a, b);\n} catch (e) {\n  if (e.message === 'Matrices have incompatible shape for multiplication') {\n    c = dot(a, t(b)); // orientation was wrong; retry transposed\n  } else {\n    throw e;\n  }\n}","preventionTips":["Apply the rule columns(left) === rows(right) whenever operand order changes","Keep feature-count constants in one place and assert weight-matrix width against them","Wrap vectors consistently (row as [[x, y]], column as [[x], [y]]) across the codebase"],"tags":["matrix","multiplication","linear-algebra","dimension-mismatch","math"],"backgroundTag":"matrix-multiplication-dimension-mismatch","analyzedSha":"85293e3e2b88f4d2ce330d956b139cf628aa1e82","analyzedAt":"2026-08-24T05:59:10.417Z","schemaVersion":2},"datasetVersion":"2026-08-24T07:17:09.176Z"}