/** * Eliminate the columns corresponding to a list of eliminated parameters. * @param M the constraints matrix whose columns are to be removed * @param nbVars an offset to be added to the ranks of the variables to be * removed * @param elimParms the list of ranks of the variables to be removed * @param newM (output) the matrix without the removed columns */ void Constraints_removeElimCols(Matrix * M, unsigned int nbVars, unsigned int *elimParms, Matrix ** newM) { unsigned int i, j, k; if (elimParms[0]==0) { Matrix_clone(M, newM); return; } if ((*newM)==NULL) { (*newM) = Matrix_Alloc(M->NbRows, M->NbColumns - elimParms[0]); } else { assert ((*newM)->NbColumns==M->NbColumns - elimParms[0]); } for (i=0; i< M->NbRows; i++) { value_assign((*newM)->p[i][0], M->p[i][0]); /* kind of cstr */ k=0; Vector_Copy(&(M->p[i][1]), &((*newM)->p[i][1]), nbVars); for (j=0; j< M->NbColumns-2-nbVars; j++) { if (j!=elimParms[k+1]) { value_assign((*newM)->p[i][j-k+nbVars+1], M->p[i][j+nbVars+1]); } else { k++; } } value_assign((*newM)->p[i][(*newM)->NbColumns-1], M->p[i][M->NbColumns-1]); /* cst part */ } } /* Constraints_removeElimCols */
Matrix* Matrix_minor(Matrix *mat, int x, int y){ Matrix *temp = Matrix_clone(mat); Matrix *newmat = Matrix_create(temp->rows - 1, temp->cols - 1); int i,j; int n = temp->rows; int m = temp->cols; int cnt = 0; double *myArr = (double*)malloc((n - 1) * (m - 1) * sizeof(double)); for(i = 0; i < n; i++){ for(j = 0; j < m; j++){ if(i != x && j != y){ myArr[cnt] = Matrix_get(temp,i,j); cnt++; } } } cnt = 0; for(i = 0; i < n - 1; i++){ for(j = 0; j < m - 1; j++){ Matrix_set(newmat,i,j,myArr[cnt]); cnt++; } } return newmat; }
Matrix *Matrix_inverse(Matrix *mat){ double det=Matrix_determinant(mat); if(mat->rows != mat->cols || det == 0.0){ return Matrix_create(mat->rows, mat->cols); } Matrix *temp = Matrix_clone(mat); int n = temp->rows; int m = temp->cols; int i,j; double tempdet,val; Matrix *Cofactor = Matrix_create(n, m); for(j = 0; j < m; j++){ for(i = 0; i < n; i++){ Matrix *Mintemp = Matrix_minor(temp,i, j); tempdet = Matrix_determinant(Mintemp); Matrix_set(Cofactor,i,j,tempdet); } } Cofactor = Matrix_transpose(Cofactor); for(i = 0; i < n; i++){ for(j = 0; j < m; j++){ val=Matrix_get(Cofactor,i,j) * pow(-1.0,(i+j)) /det; if(isnan(val)) val=0; Matrix_set(Cofactor,i,j, val); //Cofactor.setValue(i, j, (Cofactor.getValue(i, j) * Math.pow(-1D, i + j + 2)) / det); } } return Cofactor; }
Matrix *Matrix_echelon(Matrix* m){ int cols=m->cols; int rows=m->rows; int i=0,j=0,k=0; Matrix *temp=Matrix_clone(m); double pivot; for (i=0;i<rows;i++){ for(j = i + 1;j<rows;j++){ pivot = -1*Matrix_get(temp,j,i) / Matrix_get(temp,i,i); for(k = 0; k < cols; k++){ Matrix_set(temp,j,k, Matrix_get(temp,i,k) * pivot + Matrix_get(temp,j,k)); } } } return(temp); }