TheAlgorithms/JavaScript · error · Error

Input is not a valid 2D matrix.

Error message

Input is not a valid 2D matrix.

What it means

The rowEchelon function computes the row echelon form of a matrix. The guard delegates to isMatrixValid() which checks structural integrity (non-empty, rectangular shape). If the matrix is ragged, empty, or structurally invalid, the error is thrown before any row operations begin.

Source

Thrown at Maths/RowEchelon.js:112

// Subtract one row from another row
const subtractRow = (currentRow, fromRow, matrix) => {
  let numCols = matrix[0].length
  for (let j = 0; j < numCols; j++) {
    matrix[fromRow][j] -= matrix[currentRow][j]
  }
}

// Check if two numbers are equal within a given tolerance
const isTolerant = (a, b, tolerance) => {
  const absoluteDifference = Math.abs(a - b)
  return absoluteDifference <= tolerance
}

const rowEchelon = (matrix) => {
  // Check if the input matrix is valid; if not, throw an error.
  if (!isMatrixValid(matrix)) {
    throw new Error('Input is not a valid 2D matrix.')
  }

  let numRows = matrix.length
  let numCols = matrix[0].length
  let result = matrix

  // Iterate through the rows (i) and columns (j) of the matrix.
  for (let i = 0, j = 0; i < numRows && j < numCols; ) {
    // If the current column has all zero elements below the current row,
    // move to the next column.
    if (!checkNonZero(i, j, result)) {
      j++
      continue
    }

    // Select a pivot element and normalize the current row.
    selectPivot(i, j, result)
    let factor = 1 / result[i][j]

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Ensure the matrix is a non-empty rectangular 2D array.
  2. Pad or trim ragged rows to equal length before calling.
  3. Validate matrix structure with an isMatrixValid-equivalent pre-check.

Example fix

// before
rowEchelon([[1, 2], [3]])
// after
rowEchelon([[1, 2], [3, 0]])
Defensive patterns

Strategy: validation

Validate before calling

const isValidMatrix = (m) =>
  Array.isArray(m) &&
  m.length > 0 &&
  m.every((row) => Array.isArray(row) && row.length === m[0].length)
if (!isValidMatrix(matrix)) {
  throw new TypeError('Input must be a non-empty rectangular 2D matrix')
}
rowEchelon(matrix)

Type guard

const isRectangularMatrix = (m) =>
  Array.isArray(m) &&
  m.length > 0 &&
  m.every((r) => Array.isArray(r) && r.length === m[0].length)

Prevention

When it happens

Trigger: Calling rowEchelon([]), rowEchelon([[1,2],[3]]), rowEchelon([[]]), or rowEchelon(null). Ragged arrays (rows of differing lengths) and empty matrices trigger this error.

Common situations: Ragged matrices from inconsistent data parsing, empty arrays from filtered datasets, or matrices with rows of different lengths from CSV/JSON ingestion.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/0f0c8d7d8076b07e. Report an issue: GitHub.