Click here to Skip to main content
15,307,242 members
Articles / Programming Languages / C#
Tip/Trick
Posted 20 May 2012

Tagged as

Stats

79.6K views
11 bookmarked

Linear Equation Solver - Gaussian Elimination (C#)

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
22 May 2012CPOL
Linear equation solver - Gaussian Elimination.

Introduction 

This code implements the Gaussian elimination algorithm in C#.

Background

Since I was unable to find this algo in C#, I wrote it on my own.

Using the code

Simply copy and paste the code to your project. If you prefer double precision, replace all occurances of "float" with "double".

C#
public static class LinearEquationSolver
{
    /// <summary>Computes the solution of a linear equation system.</summary>
    /// <param name="M">
    /// The system of linear equations as an augmented matrix[row, col] where (rows + 1 == cols).
    /// It will contain the solution in "row canonical form" if the function returns "true".
    /// </param>
    /// <returns>Returns whether the matrix has a unique solution or not.</returns>
    public static bool Solve(float[,] M)
    {
        // input checks
        int rowCount = M.GetUpperBound(0) + 1;
        if (M == null || M.Length != rowCount * (rowCount + 1))
          throw new ArgumentException("The algorithm must be provided with a (n x n+1) matrix.");
        if (rowCount < 1)
          throw new ArgumentException("The matrix must at least have one row.");

        // pivoting
        for (int col = 0; col + 1 < rowCount; col++) if (M[col, col] == 0)
        // check for zero coefficients
        {
            // find non-zero coefficient
            int swapRow = col + 1;
            for (;swapRow < rowCount; swapRow++) if (M[swapRow, col] != 0) break;

            if (M[swapRow, col] != 0) // found a non-zero coefficient?
            {
                // yes, then swap it with the above
                float[] tmp = new float[rowCount + 1];
                for (int i = 0; i < rowCount + 1; i++)
                  { tmp[i] = M[swapRow, i]; M[swapRow, i] = M[col, i]; M[col, i] = tmp[i]; }
            }
            else return false; // no, then the matrix has no unique solution
        }

        // elimination
        for (int sourceRow = 0; sourceRow + 1 < rowCount; sourceRow++)
        {
            for (int destRow = sourceRow + 1; destRow < rowCount; destRow++)
            {
                float df = M[sourceRow, sourceRow];
                float sf = M[destRow, sourceRow];
                for (int i = 0; i < rowCount + 1; i++)
                  M[destRow, i] = M[destRow, i] * df - M[sourceRow, i] * sf;
            }
        }

        // back-insertion
        for (int row = rowCount - 1; row >= 0; row--)
        {
            float f = M[row,row];
            if (f == 0) return false;

            for (int i = 0; i < rowCount + 1; i++) M[row, i] /= f;
            for (int destRow = 0; destRow < row; destRow++)
              { M[destRow, rowCount] -= M[destRow, row] * M[row, rowCount]; M[destRow, row] = 0; }
        }
        return true;
    }
}

Changes

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

janismac
Germany Germany
No Biography provided

Comments and Discussions

 
GeneralMy vote of 4 Pin
Member 1536803613-Dec-21 15:34
MemberMember 1536803613-Dec-21 15:34 
GeneralMy vote of 3 Pin
Member 1210123021-Jun-17 0:52
MemberMember 1210123021-Jun-17 0:52 
Questionimprovements Pin
a_voronin27-Oct-16 14:03
Membera_voronin27-Oct-16 14:03 
Questionimprovements Pin
a_voronin27-Oct-16 14:00
Membera_voronin27-Oct-16 14:00 
GeneralMy vote of 5 Pin
Member 791511423-Jan-16 14:56
MemberMember 791511423-Jan-16 14:56 
QuestionProblem with search for non-zero pivot element Pin
Member 1035586924-Jan-14 17:47
MemberMember 1035586924-Jan-14 17:47 
NewsSolving a System of Linear Equation Pin
WiiMaxx15-Jul-13 2:58
MemberWiiMaxx15-Jul-13 2:58 
BugIncorrect calculation Pin
elw00d12325-Sep-12 3:11
Memberelw00d12325-Sep-12 3:11 
SuggestionFurther C# packages on Gaussian Elimination and Linear Matrix Algebra in general Pin
akemper21-May-12 11:33
Memberakemper21-May-12 11:33 
QuestionPInvoke and ACML is a solid solution Pin
Jonathan Langdon21-May-12 7:04
MemberJonathan Langdon21-May-12 7:04 
QuestionSuggestion Pin
jarvisa21-May-12 0:14
Memberjarvisa21-May-12 0:14 
QuestionMost of us use 3rd party libraries... Pin
Andreas Gieriet20-May-12 22:10
professionalAndreas Gieriet20-May-12 22:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.