{"record":{"id":"fb1fe26f4827f9c4","repo":"TheAlgorithms/C-Sharp","slug":"source-matrix-is-not-square-shaped","errorCode":null,"errorMessage":"Source matrix is not square shaped.","messagePattern":"Source matrix is not square shaped\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Numeric/Decomposition/LU.cs","lineNumber":21,"sourceCode":"/// <summary>\n///     LU-decomposition factors the \"source\" matrix as the product of lower triangular matrix\n///     and upper triangular matrix.\n/// </summary>\npublic static class Lu\n{\n    /// <summary>\n    ///     Performs LU-decomposition on \"source\" matrix.\n    ///     Lower and upper matrices have same shapes as source matrix.\n    ///     Note: Decomposition can be applied only to square matrices.\n    /// </summary>\n    /// <param name=\"source\">Square matrix to decompose.</param>\n    /// <returns>Tuple of lower and upper matrix.</returns>\n    /// <exception cref=\"ArgumentException\">Source matrix is not square shaped.</exception>\n    public static (double[,] L, double[,] U) Decompose(double[,] source)\n    {\n        if (source.GetLength(0) != source.GetLength(1))\n        {\n            throw new ArgumentException(\"Source matrix is not square shaped.\");\n        }\n\n        var pivot = source.GetLength(0);\n        var lower = new double[pivot, pivot];\n        var upper = new double[pivot, pivot];\n\n        for (var i = 0; i < pivot; i++)\n        {\n            for (var k = i; k < pivot; k++)\n            {\n                double sum = 0;\n\n                for (var j = 0; j < i; j++)\n                {\n                    sum += lower[i, j] * upper[j, k];\n                }\n\n                upper[i, k] = source[i, k] - sum;","sourceCodeStart":3,"sourceCodeEnd":39,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Numeric/Decomposition/LU.cs#L3-L39","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify the matrix is square before calling: source.GetLength(0) == source.GetLength(1).","If your matrix is augmented (n x n+1), strip the last column before decomposing, or call LU.Eliminate with the coefficients vector separately.","Fix the matrix construction/loading code so the stored array is truly n x n."],"exampleFix":"// before\nvar (l, u) = LU.Decompose(augmentedMatrix); // n x (n+1), throws\n// after\nif (a.GetLength(0) != a.GetLength(1))\n    throw new InvalidOperationException(\"Coefficient matrix must be square\");\nvar (l, u) = LU.Decompose(a);","handlingStrategy":"validation","validationCode":"if (source == null || source.GetLength(0) != source.GetLength(1))\n    throw new ArgumentException(\"LU.Decompose requires a square matrix\");","typeGuard":"static bool IsSquare(double[,] m) => m != null && m.GetLength(0) == m.GetLength(1);","tryCatchPattern":"try\n{\n    var (l, u) = LU.Decompose(source);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"not square\"))\n{\n    // report dimension error to caller\n}","preventionTips":["Check GetLength(0) == GetLength(1) at matrix construction time.","Strip augmented columns before factorization.","Assert square shape in unit tests for matrix-loading code."],"tags":["matrix","linear-algebra","argument-validation","csharp"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}