最近寫了一個C程式 ------------- 矩陣的基本運算。
包括四則運算, 求逆, rref(行最簡型), 轉置。
並有幾個實際應用例子, 求解方程組, 線性迴歸, 線性規劃進行中中。
貼出來請大牛們指點指點。就貼最難的一個, rref吧。
/************************************ * pTag is the pivots tag * if 1, the column is pivot * and 0, the column is not pivot * Return: *return elimination matrix*************************************/matrixrref(matrix A, int *pTag) // reduced row echelon form{ // initialize Elimination matrix matrix E = Imat(A->rows); double **MA = A->data; double **ME = E->data; double e[A->rows];// factor of reduced // echelon loop int k; for (int pivots = 0, j = 0; j < A->cols && pivots < A->rows; j++) {if (MA[j][pivots] == 0.0){ // if this element is 0.0, find a nonzero element behind in j's column for (k = pivots + 1; k < A->rows && MA[j][k] == 0.0; k++); // row swap if find else operate next line if (k != A->rows) {RowSwap(A, pivots, k);RowSwap(E, pivots, k); } else {pTag[j] = 0;continue; }}// eliminatepTag[j] = 1;for (int i = 0; i < A->rows; i++) e[i] = (i == pivots ? 0 : MA[j][i] / MA[j][pivots]);for (int col = 0; col < A->cols; col++) for (int row = 0; row < A->rows; row++)MA[col][row] -= e[row] * MA[col][pivots];for (int col = 0; col < E->cols; col++) for (int row = 0; row < E->rows; row++)ME[col][row] -= e[row] * ME[col][pivots];pivots++; } // normalise after echelon, maybe can layout it to // echelon loop, but it will reduce the precision double fac; for (int i = 0, k = 0; i < A->rows; i++) {while (pTag[k++] == 0);fac = MA[k - 1][i];for (int j = 0; j < E->cols; j++) ME[j][i] /= fac;for (int j = 0; j < A->cols; j++) MA[j][i] /= fac; } return E;}
上傳半天不見有反應, CSDN, 有點怪. 完整曆程及樣本請到這裡下載
這裡