{"record":{"id":"b7509e0b7e8d0501","repo":"trekhleb/javascript-algorithms","slug":"matrices-have-different-dimensions","errorCode":null,"errorMessage":"Matrices have different dimensions","messagePattern":"Matrices have different dimensions","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/algorithms/math/matrix/Matrix.js","lineNumber":69,"sourceCode":"  }\n};\n\n/**\n * Validates that matrices are of the same shape.\n *\n * @param {Matrix} a\n * @param {Matrix} b\n * @trows {Error}\n */\nexport const validateSameShape = (a, b) => {\n  validateType(a);\n  validateType(b);\n\n  const aShape = shape(a);\n  const bShape = shape(b);\n\n  if (aShape.length !== bShape.length) {\n    throw new Error('Matrices have different dimensions');\n  }\n\n  while (aShape.length && bShape.length) {\n    if (aShape.pop() !== bShape.pop()) {\n      throw new Error('Matrices have different shapes');\n    }\n  }\n};\n\n/**\n * Generates the matrix of specific shape with specific values.\n *\n * @param {Shape} mShape - the shape of the matrix to generate\n * @param {function({CellIndex}): Cell} fill - cell values of a generated matrix.\n * @returns {Matrix}\n */\nexport const generate = (mShape, fill) => {\n  /**","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/trekhleb/javascript-algorithms/blob/85293e3e2b88f4d2ce330d956b139cf628aa1e82/src/algorithms/math/matrix/Matrix.js#L51-L87","documentation":"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.","triggerScenarios":"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]).","commonSituations":"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.","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"],"exampleFix":"// before\nimport { add } from './src/algorithms/math/matrix/Matrix';\nconst result = add([[1, 2], [3, 4]], [1, 2]);\n// throws: shapes [2,2] vs [2]\n\n// after\nconst result = add([[1, 2], [3, 4]], [[1, 2], [1, 2]]);\n// both shapes are [2,2]","handlingStrategy":"validation","validationCode":"import { shape } from './src/algorithms/math/matrix/Matrix';\n\nconst sameRank = (a, b) => shape(a).length === shape(b).length;\nif (!sameRank(matrixA, matrixB)) {\n  throw new TypeError('rank mismatch: ' + JSON.stringify(shape(matrixA)) + ' vs ' + JSON.stringify(shape(matrixB)));\n}\nconst sum = add(matrixA, matrixB);","typeGuard":"import { shape } from './src/algorithms/math/matrix/Matrix';\n\nconst isMatrixOfRank = (m, rank) => Array.isArray(m) && shape(m).length === rank;\n// usage: isMatrixOfRank(a, 2) && isMatrixOfRank(b, 2)","tryCatchPattern":"try {\n  result = add(a, b);\n} catch (e) {\n  if (e.message === 'Matrices have different dimensions') {\n    throw new Error('add(): rank mismatch ' + JSON.stringify(shape(a)) + ' vs ' + JSON.stringify(shape(b)), { cause: e });\n  }\n  throw e;\n}","preventionTips":["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"],"tags":["matrix","shape-validation","math","rank-mismatch"],"backgroundTag":"matrix-shape-mismatch","analyzedSha":"85293e3e2b88f4d2ce330d956b139cf628aa1e82","analyzedAt":"2026-08-24T05:59:10.417Z","schemaVersion":2},"datasetVersion":"2026-08-24T07:17:09.176Z"}