TheAlgorithms/C-Sharp · error · ArgumentException

Dimensions of matrices must be the same

Error message

Dimensions of matrices must be the same

What it means

MatrixExtensions.Subtract performs element-wise subtraction, which requires both matrices to have identical dimensions. If either dimension differs (lhs.GetLength(0/1) != rhs.GetLength(0/1)) it throws ArgumentException because element-wise ops are undefined for mismatched shapes.

Solutions

  1. Check lhs and rhs have identical GetLength(0) and GetLength(1) before subtracting
  2. Resize or slice one matrix to match the other if the intent is element-wise on a common region
  3. Implement explicit broadcasting logic if NumPy-style semantics are desired

Example fix

// before
var diff = a.Subtract(b); // a: 2x3, b: 3x3 -> throws
// after
if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
{
    throw new ArgumentException("Matrices must have the same dimensions for subtraction.");
}
var diff = a.Subtract(b);
Defensive patterns

Strategy: validation

Validate before calling

if (lhs.GetLength(0) != rhs.GetLength(0) || lhs.GetLength(1) != rhs.GetLength(1))
    throw new ArgumentException("Element-wise subtract requires identical shapes.");
var diff = lhs.Subtract(rhs);

Try / catch

try { var diff = lhs.Subtract(rhs); }
catch (ArgumentException) { /* reshape or report dimension mismatch upstream */ }

Prevention

When it happens

Trigger: Calling lhs.Subtract(rhs) where row counts or column counts differ, e.g. a 2x3 minus a 3x2, or a batch result minus a single row.

Common situations: Subtracting matrices produced from different-sized inputs earlier in a pipeline; broadcasting a 1D row against a 2D matrix expecting NumPy-like broadcasting; off-by-one in generated matrix sizes.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/7b7728d34b5d9e60. Report an issue: GitHub.

Appendix: source

Thrown at Utilities/Extensions/MatrixExtensions.cs:115

            result[i] = resultMatrix[i, 0];
        }

        return result;
    }

    /// <summary>
    ///     Performs matrix subtraction.
    /// </summary>
    /// <param name="lhs">The LHS matrix.</param>
    /// <param name="rhs">The RHS matrix.</param>
    /// <returns>The difference of the two matrices.</returns>
    /// <exception cref="ArgumentException">Dimensions of matrices do not match.</exception>
    public static double[,] Subtract(this double[,] lhs, double[,] rhs)
    {
        if (lhs.GetLength(0) != rhs.GetLength(0) ||
            lhs.GetLength(1) != rhs.GetLength(1))
        {
            throw new ArgumentException("Dimensions of matrices must be the same");
        }

        var result = new double[lhs.GetLength(0), lhs.GetLength(1)];
        for (var i = 0; i < lhs.GetLength(0); i++)
        {
            for (var j = 0; j < lhs.GetLength(1); j++)
            {
                result[i, j] = lhs[i, j] - rhs[i, j];
            }
        }

        return result;
    }

    /// <summary>
    ///     Performs an element by element comparison on both matrices.
    /// </summary>
    /// <param name="source">Source left matrix.</param>

View on GitHub (pinned to 96e2905cab)