void Matrix::rref() { int l = 0; int r = 0; int i = 0; double v = 0.0; for (r = 0; r < nRows; r++) { if (nCols <= l) { break; } i = r; while (get(i + 1, l + 1) == 0.0) { i++; if (nRows == i) { i = r; l++; if (nCols == l) { break; } } } rowSwap(i + 1, r + 1); v = get(r + 1, l + 1); if (v != 0.0) { rowMul(r + 1, 1 / v); } for (i = 0; i < nRows; i++) { if (i != r) { v = get(i + 1, l + 1); rowAddMul(i + 1, r + 1, 0 - v); } } l++; } }
void setMatrix(double **A, int n, int m){ int i, j; for(i = 0;i<n-1;i++){ for(j=i+1;j<n;j++){ if(*(*(A+i)) < *(*(A+j))){ rowSwap(A, i, j, n, m); } } } }
vector<T> gaussElim<T>::operator()(matrix<T>& A, vector<T>& b) { vector<T> x(b); int p = 1; T scalar; T* s = new T[A.getRows()]; for(int i = 0; i < A.getRows(); i++) { s[i] = 0; for(int j = 0; j < A.getCols(); j++) { if(s[i] < abs(A(i+1,j+1))) { s[i] = abs(A(i+1, j+1)); } } } for(int i = 1; i <= A.getCols(); i++) { p = i; for(int k = i + 1; k <= A.getCols(); k++) { if(abs(A(p, i))/s[p-1] < abs(A(k, i))/s[k-1]) { p = k; } } if(p != i) { rowSwap(i, p, A, b); } for(int k = i + 1; k <= A.getCols(); k++) { scalar = -A(k,i)/A(i,i); rowAdd(k, i, scalar, A, b); A(k,i) = 0; } } for(int i = A.getCols(); i > 0; i--) { scalar = 0; for(int j = i; j < A.getCols(); j++) { scalar = scalar + x[j] * A(i,j+1); } if(A(i, i) != 0) { x[i - 1] = (b[i - 1] - scalar)/A(i,i); } } delete [] s; return x; }
void matrixRREF(Matrix m) { int prealloc = alloc_matrix; int pivotCol = 0; int pivotRow = 0; int row; FTYPE absVal; int tmp = 0; while(1) { /* Select the row with the largest absolute value, or move to the next row if there is no value int the column */ absVal = 0.0; while( absVal == 0.0 && pivotCol < m->col_dim) { absVal = ABS(ME(m,pivotRow,pivotCol)); tmp = pivotRow; for(row = pivotRow+1; row < m->row_dim; row++) { if( ABS(ME(m,row,pivotCol)) > absVal ) { absVal = ABS(ME(m,row,pivotCol)); tmp = row; } } if(absVal == 0) { pivotCol++; } } /* return if the RREF has been found */ if( pivotCol >= m->col_dim || pivotRow >= m->row_dim) return; /* make sure that the pivot row is in the correct position */ if(pivotRow != tmp) rowSwap(m,tmp,pivotRow); /* rescale the Pivot Row */ rowMult( m, pivotRow,1.0/ME(m,pivotRow,pivotCol) ); /* This part of the algorithm is not as effecent as it could be, but it works for now. */ for(row = 0; row < m->row_dim; row++) { if(row != pivotRow) { rowMultAdd(m,pivotRow,row,-ME(m,row,pivotCol)); } } pivotRow++; pivotCol++; } if(prealloc != alloc_matrix) { printf("Error deallocating matricies <%s>: pre=%d post=%d",__FUNCTION__, prealloc, alloc_matrix); exit(1); } }