mercredi 31 octobre 2018

My Gauss Elimination function is producing garbage values

I am trying to implement Gauss Elimination before trying to implement other matrix operations and I went with a pretty straightforward idea (basically translated the process I do on paper with matrices into code) and it's this:

Matrix resultVector(this->mRow, 1), matA(this->mRow, this->mColumn);
matA = *this;
for(int i=0; i < this->mRow; i++)
} 
    double pivotElement = matA.mMatrix[i][i];
    for(int j=i+1; j < this->mRow; j++)
    {
        double coeff = pivotElement/(double)matA.mMatrix[j][i];
        for(int k=i; k < this->mRow; k++)
        {
            matA.mMatrix[j][k] *= coeff;
            matA.mMatrix[j][k] -= matA.mMatrix[i][k];
        }
    }
}

Matrix is a class with three private variables. mRow, mColumn and mMatrix.

mMatrix is initialized by a default and a parameterized constructor as a dynamically allocated 2D array.

All of this is to solve square matrices this is why I chose to use mRow constantly and interchangeably with mColumn.

Idea was:

1)select pivot element.

2)move vertically from i+1 to mRow-1 (from first row beneath pivot row to last row)

3)evaluate the coefficient needed for the mMatrix[j][i] element to be equal to *mMatrix[i][i]

4)start moving horizontally from i to mRow

5)starting from the [j][k]-th element, multiply it by the coefficient then subtract.

note: this program does not yet take the b vector into account and does not print out the resultVector. My problem is specifically that this program does not correctly produce an upper-triangular matrix.

sample input/output:

1 2 3 == 1 2 3

2 -3 2 == 0 -3.5 -2

3 1 -1 == 2.98023e-008 -2.17557e-007 -5

correct input/output:

1 2 3 == 1 2 3

2 -3 2 == 0 1 2

3 1 -1 == 0 0 10

Aucun commentaire:

Enregistrer un commentaire