TheAlgorithms/C-Sharp · error · ArgumentException

Source matrix is not square shaped.

Error message

Source matrix is not square shaped.

What it means

LU.Decompose(source) performs LU factorization, which is defined only for square (n x n) matrices. When source.GetLength(0) != source.GetLength(1) the method throws ArgumentException 'Source matrix is not square shaped.' It guards against factorizing rectangular input, which has no LU decomposition in this implementation.

Solutions

  1. Verify the matrix is square before calling: source.GetLength(0) == source.GetLength(1).
  2. If your matrix is augmented (n x n+1), strip the last column before decomposing, or call LU.Eliminate with the coefficients vector separately.
  3. Fix the matrix construction/loading code so the stored array is truly n x n.

Example fix

// before
var (l, u) = LU.Decompose(augmentedMatrix); // n x (n+1), throws
// after
if (a.GetLength(0) != a.GetLength(1))
    throw new InvalidOperationException("Coefficient matrix must be square");
var (l, u) = LU.Decompose(a);
Defensive patterns

Strategy: validation

Validate before calling

if (source == null || source.GetLength(0) != source.GetLength(1))
    throw new ArgumentException("LU.Decompose requires a square matrix");

Type guard

static bool IsSquare(double[,] m) => m != null && m.GetLength(0) == m.GetLength(1);

Try / catch

try
{
    var (l, u) = LU.Decompose(source);
}
catch (ArgumentException ex) when (ex.Message.Contains("not square"))
{
    // report dimension error to caller
}

Prevention

When it happens

Trigger: Passing an m x n matrix with m != n to LU.Decompose, e.g. a 3x4 data matrix, a freshly allocated rectangular array, or a matrix built from rows of differing logical width.

Common situations: Loading a coefficient matrix from CSV/user input where the data is actually augmented (n x n+1) or rectangular; concatenating rows into a matrix without checking dimensions; using a design matrix (taller than wide) by mistake instead of the square system matrix.

Understand the failure class

Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.

Related errors


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

Appendix: source

Thrown at Algorithms/Numeric/Decomposition/LU.cs:21

/// <summary>
///     LU-decomposition factors the "source" matrix as the product of lower triangular matrix
///     and upper triangular matrix.
/// </summary>
public static class Lu
{
    /// <summary>
    ///     Performs LU-decomposition on "source" matrix.
    ///     Lower and upper matrices have same shapes as source matrix.
    ///     Note: Decomposition can be applied only to square matrices.
    /// </summary>
    /// <param name="source">Square matrix to decompose.</param>
    /// <returns>Tuple of lower and upper matrix.</returns>
    /// <exception cref="ArgumentException">Source matrix is not square shaped.</exception>
    public static (double[,] L, double[,] U) Decompose(double[,] source)
    {
        if (source.GetLength(0) != source.GetLength(1))
        {
            throw new ArgumentException("Source matrix is not square shaped.");
        }

        var pivot = source.GetLength(0);
        var lower = new double[pivot, pivot];
        var upper = new double[pivot, pivot];

        for (var i = 0; i < pivot; i++)
        {
            for (var k = i; k < pivot; k++)
            {
                double sum = 0;

                for (var j = 0; j < i; j++)
                {
                    sum += lower[i, j] * upper[j, k];
                }

                upper[i, k] = source[i, k] - sum;

View on GitHub (pinned to 96e2905cab)