0 Replies - 1618 Views - Last Post: 04 November 2011 - 12:59 PM

#1 B-rock  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-November 11

Matrix Inversion - catching a pivot element of 0

Posted 04 November 2011 - 12:59 PM

I'm currently working on a implementing a matrix inversion method for a Matrix class in C++. One thing that isn't implemented is a check for when the pivot element is 0, meaning I will need to swap the rows (likely with the row just beneath it).

Here is what I have for far for the Inversion method:
Matrix Matrix:: invert()
{
	if (rows != cols) {         // Check for square matrix
		cout << "Matrix must be square." << endl;
		exit(1);
	}

	double ratio, sum;
	int i, j, k;
	Matrix T1(rows, cols*2);		// New temp identity matrix of same order
	Matrix F(rows, cols);				// Final Inverted Matrix
    
	// Add Identity Matrix
	for(i = 1; i <= rows; i++){
		for(j = rows; j <= 2*rows; j++){
			if(i == (j-cols)){
				T1.el[i][j] = 1.0;
			}
			else
				T1.el[i][j] = 0.0;
		}
	}

    // Add original Matrix to 1st half of Temp Matrix
	for (i = 1; i <=rows; i++) {       
		for(j=1;j<=rows; j++) {
			T1.el[i][j] = el[i][j];
		}
	}

	cout << "\n\nOriginal matrix with added Identity Matrix" << endl;
	for (i = 1; i <=rows; i++) {
		cout << setw(5);
		for(j=1;j<=rows*2; j++) {
			cout << T1.el[i][j] << setw(6);
		}
		cout << endl;
	}

	double temp;
	// Row Operations
	for(i = 1; i <= rows; i++){
		for(j = 1; j <= rows; j++){
			if(i != j) {
				ratio = T1.el[j][i]/T1.el[i][i];
				for(k = 1; k <= 2*rows; k++) {
					T1.el[j][k] -= ratio * T1.el[i][k];
				}
			}
		}
	}

	// Check for Singular Matrix
    double det = 1;
    for (i = 1; i <= rows; i++){
		det *= T1.el[i][i];
    }
	if (det == 0){
        cout << "Detected Singulgar Matrix." << endl;
        //exit(1);
	}

	// backwards substitutions
	for(i = 1; i <= rows; i++){
		sum = T1.el[i][i];
		for(j = i+1; j <= 2*rows; j++){
			T1.el[i][j] /= sum;
		}
	}

	// Copy to return Matrix
	for(i=1; i<=rows; i++){
		for (j=1; j<=rows; j++) {
            F.el[i][j] = T1.el[i][j+cols];
		}
	}

	return F;
}



How or where would I go about adding this functionality/check?

Thanks.

Brock

Is This A Good Question/Topic? 0
  • +

Page 1 of 1