//------------------------------------------------------------------------------ // pivotRow //------------------------------------------------------------------------------ bool Matrix::pivotRow(const unsigned int r, const unsigned int c) { bool l1 = (r < rows-1); bool l2 = (c < cols); bool ok = false; if (l1 && l2) { unsigned int refrow = r; double max = std::fabs(getElem(r,c)); for (unsigned int i=r+1; i<rows; i++) { double val = std::fabs(getElem(i,c)); if (val > max) { refrow = i; max = val; } } if (r != refrow) { swapRow(r, refrow); } ok = true; } return ok; }
/** * @param matrix: A list of lists of integers * @return: Void */ void rotate(vector<vector<int> > &matrix) { // write your code here int n = matrix.size(); swapDig(matrix); int i = 0; int j = n-1; while(i < j){ swapRow(matrix, i++, j--); } }
bool CoordTransform::swapNonZero(int r) { if(m[r][r] != 0.0) return true; int cur = r; while(m[cur][r] == 0.0) { cur++; if(cur >= 3) { return false; } } swapRow(cur, r); return true; }
int gaussJordan(Matrix *mat) { int i, j,k, i_max; double tmp; for (k = 0; k < mat -> size; k++) { i_max = pivMax(mat, k); //printf("i_max: %d k: %d\n",i_max,k); assert(accessMat(mat, k, i_max) != 0); if(k != i_max) swapRow(mat, k, i_max); for (j = k + 1; j < mat -> size; j++) { for (i = k + 1; i < mat -> size * 2; i++) { tmp = accessMat(mat, i, j) - accessMat(mat, i, k) * (accessMat(mat, k, j) / accessMat(mat, k, k)); insertMat(mat, i, j, tmp); } insertMat(mat,k,j,0); } } backSub(mat); inverse(mat); return 0; }
int main(int argc, char const *argv[]) { int matrixSize = strtol(argv[1], NULL, 10); int coreCount = omp_get_num_procs(); int threadCount = strtol(argv[2], NULL, 10); double startTime, finishTime; double **a_augmented, **a; // n x n Matrix as a 2D array double diagonalElement, bestElement, factor; int bestRowIndex = 0; // used in partial pivoting (index of row having greatest absolute value) int i, j, k; // for loop counters double *x; // Solutions double *b; printf("Matrix Size: %d\n", matrixSize); printf("Number of Cores: %d\n", coreCount); #pragma omp parallel num_threads(threadCount) { if (omp_get_thread_num() == 0) printf("Thread Count: %d\n", omp_get_num_threads()); } // Start Timer startTime = omp_get_wtime(); // Allocate memory // a_augmented will be the augmented matrix a_augmented = (double **) malloc(matrixSize * sizeof(double *)); // a will be the randomly generated matrix a = (double **) malloc(matrixSize * sizeof(double *)); x = (double *) malloc(matrixSize * sizeof(double)); b = (double *) malloc(matrixSize * sizeof(double)); if (DEBUG == 1) Read_matrix(&a, &a_augmented, matrixSize); else Gen_matrix(&a, &a_augmented, matrixSize, threadCount); // a will not be modified after this point // Only the a_augmented will be modified // Display generated matrix: displayMatrix(a, matrixSize); for (i = 0; i < matrixSize - 1; ++i) { // Partial Pivoting: // the algorithm selects the entry with largest absolute value from // the column of the matrix that is currently being considered as // the pivot element. // Diagonal Element diagonalElement = a_augmented[i][i]; // debug_printf("diagonalElement%d = %f\n", i, diagonalElement); // Find the best row (the one with the largest absolute value in the // column being worked on) bestRowIndex = i; bestElement = diagonalElement; for (j = i + 1; j < matrixSize; ++j) { if (fabs(a_augmented[j][i]) > fabs(bestElement)) { bestRowIndex = j; bestElement = a_augmented[j][i]; // debug_printf("bestElement = %f\n", a_augmented[j][i]); } } // Swap the rows if (i != bestRowIndex) { // debug_printf("Row %d needs to be swapped with Row %d\n", i, bestRowIndex ); swapRow(&a_augmented[i], &a_augmented[bestRowIndex]); // Update the diagonal element diagonalElement = a_augmented[i][i]; // debug_printf("diagonalElement%d = %f\n", i, diagonalElement); // displayMatrix(a_augmented, matrixSize); } // End of Partial Pivoting // To make the diagonal element 1, // divide the whole row with the diagonal element // debug_printf("Row %d = Row %d / %f\n", i, i, diagonalElement); for (j = 0; j < matrixSize + 1; ++j) { a_augmented[i][j] = a_augmented[i][j] / diagonalElement; } // Force the diagonal to be 1 (to avoid any roundoff errors in dividing above) a_augmented[i][i] = 1; diagonalElement = 1; // debug_printf("Annihilation of column %d...\n", i); // Annihilation: Zero all the elements in the column below the diagonal element #pragma omp parallel for num_threads(threadCount) \ default(none) private(j, factor, k) shared(i, matrixSize, a_augmented) for (j = i + 1; j < matrixSize; ++j) { // sleep(1); factor = a_augmented[j][i]; if (factor != 0) { // debug_printf("Row %d = Row %d - %f*Row %d\n", j, j, factor, i); for (k = i; k < matrixSize + 1; ++k) { a_augmented[j][k] = a_augmented[j][k] - factor * a_augmented[i][k]; } // displayAugmentedMatrix(a, matrixSize); } } } // Make the diagonal element of the last row 1 a_augmented[matrixSize-1][matrixSize] = a_augmented[matrixSize-1][matrixSize] / a_augmented[matrixSize-1][matrixSize-1]; a_augmented[matrixSize-1][matrixSize-1] = 1; // Display augmented matrix: displayMatrix(a_augmented, matrixSize); // Back substitution (parallelized) backSubstitution(&a_augmented, matrixSize, threadCount); // Record the finish time finishTime = omp_get_wtime(); displayMatrix(a_augmented, matrixSize); // Matrix X from augmented matrix // Vector b from matrix A for (i = 0; i < matrixSize; ++i) { x[i] = a_augmented[i][matrixSize]; b[i] = a[i][matrixSize]; } // Find I^2 norm iSquaredNorm(&a, x, b, matrixSize, threadCount); // Print the time taken printf("Time taken = %f\n", finishTime - startTime); // Free memory for (i = 0; i < matrixSize; ++i) { free(a[i]); free(a_augmented[i]); } free(a); free(a_augmented); free(x); free(b); return 0; }
main() { int i,j,instanc,k=0,count1=0,count2=0; printf("\n\t Enter No. of Process(max 15):-\n"); printf("\t\t"); scanf("%d",&process); //Entering No. of Processes for(i=0;i<process;i++) { p[i]=i; } printf("\n\tEnter No. of Resources(max 10):-\n"); printf("\t\t"); scanf("%d",&resource); //No. of Resources for(i=0;i<process;i++) completed[i]=0; //Setting Flag for uncompleted Process printf("\n\tEnter No. of Available Instances\n"); for(i=0;i<resource;i++) { printf("\t\t"); scanf("%d",&instanc); avail[i]=instanc; // Storing Available instances } printf("\n\tEnter Maximum No. of instances of resources that a Process need:\n"); for(i=0;i<process;i++) { printf("\n\t For P[%d]\n",i); for(j=0;j<resource;j++) { printf("\t"); scanf("%d",&instanc); fflush(stdin); max[i][j]=instanc; } } //Entering burst time for all processes for(i=0;i<process;i++) { printf("Enter the burst time of %d process:\t",i+1); scanf("%d",&ser[i]); arrv[i] =0; } printf("\n\t Enter no. of instances already allocated to process of a resource:\n"); for(i=0;i<process;i++) { printf("\n\t For P[%d]\t\n",i); for(j=0;j<resource;j++) { printf("\t\t"); scanf("%d",&instanc); allot[i][j]=instanc; need[i][j]=max[i][j]-allot[i][j]; //calculating Need of each process } } int t; for(t=0;t<3;t++) { int var1, var2; var1= 1 + rand() / (RAND_MAX / (process - 1 + 1) + 1); var2 = 1 + rand() / (RAND_MAX / (process - 1 + 1) + 1); swapRow(var1, var2,max); swapRow(var1,var2,allot); swapRow(var1,var2,need); swapCol(var1,var2,completed); swapCol(var1,var2,p); swapCol(var1,var2,ser); bankers(t); //setting complete array to 0 for(i=0;i<process;i++) completed[i]=0; } }
void LUFactorize(matrix A, matrix *L, matrix *U){ /* Perform LU factorization of matrix A. Returns permutation of lower triangular matrix and upper triangular matrix such that L*U = A. Input: matrix A Matrix to factor. matrix L Filler for returned matrix, must be preallocated. matrix U Filler for returned matrix, must be preallocated. Output: matrix L Permutation of lower triangular factor. matrix U Upper triangular factor. */ if(A.m != A.n){ fprintf(stderr,"Input matrix must be square. Other dimensions not supported.\n") ; exit(-1); } if((L->m != A.m) || (L->n != A.n)){ fprintf(stderr, "Matrix dimensions must agree. Exiting.\n") ; exit(-1) ; } if((U->m != A.m) || (U->n != A.n)){ fprintf(stderr, "Matrix dimensions must agree. Exiting.\n") ; exit(-1) ; } int i,j,k; int n = A.n ; // zero L for(i=0; i<n; i++){ for(j=0; j<n; j++){ L->values[i][j] = 0.0 ; } } // copy A for non-destructive editing copyMatrix(A, *U) ; int *pivots = (int *) malloc(n * sizeof(int)) ; for(i=0; i < n-1; i++){ pivots[i] = getIndexOfMax(*U, i, i) ; if(i != pivots[i]) swapRow(*U, i, pivots[i]) ; for(j=i+1; j < U->n; j++) U->values[j][i] /= U->values[i][i] ; // trailing matrix update for(j=i+1; j<n; j++){ for(k=i+1; k<n; k++){ U->values[j][k] -= U->values[j][i] * U->values[i][k] ; } } } pivots[n-1] = n - 1 ; // place the result in the two separate arrays // copy diagonal entries for(i=0; i<n; i++) L->values[i][i] = 1.0 ; // copy relevant data from U to L for(j=0; j < n-1; j++){ for(i=j+1; i<n; i++){ L->values[i][j] = U->values[i][j] ; U->values[i][j] = 0.0 ; } } // permute L to make L*U = A for(i=n-1; i>=0; i--){ if(pivots[i] != i) swapRow(*L, pivots[i], i) ; } free(pivots) ; }
int main() { /************************************************************/ /* */ /* ここに課題のプログラムを書く. */ /* */ /* 関数 read_matrix() を呼ぶことで,標準入力から連立一次 */ /* 方程式の次数および各係数を読み込む.その結果, */ /* 次数が大域変数 n に, */ /* 係数行列 A と右辺ベクトル b を合わせた拡大行列 [A b] が */ /* 帯域変数 a[][] に,それぞれ格納される. */ /* なお,a[][]の内部は */ /* A → a[1][1] ... a[n][n] , */ /* b → a[1][n+1] ... a[n][n+1] */ /* のようになっている. */ /* */ /* 関数 print_matrix() は a[][] の内容を標準出力に */ /* 出力する.アルゴリズムのデバッグに活用すべし. */ /* */ /************************************************************/ /* 以下はサンプルプログラムで,行列を読み込んでそのまま出力する.*/ /* 標準入力を読み込んで,係数行列を a[][] に,次数を n に格納する */ if (read_matrix() != 0) { /* 返り値が 0 以外であればエラー */ fprintf(stderr, "input error!\n"); return -1; } /* 現在の係数行列 a[][] の内容を出力する */ print_matrix(); /* ここにガウス消去法などの課題のプログラムを書く */ // Instead of Gaussian elimination, we'll use gauss-seidel method this // These 2 variables are used to test every cases of swapping (like a // bubble sort) int rowToSwap; int rowToSwap2; int allCombinations; for (allCombinations = 0; allCombinations < n; allCombinations++) { for (rowToSwap = 1; rowToSwap < n; rowToSwap++) { for (rowToSwap2 = n; rowToSwap2 >= 1; rowToSwap2--) { double values[MAXN] = {0}; double prev_values[MAXN] = {0}; // Checking if the equations are solved for x_1, x_2 ... print_matrix(); // Repeat this loop N times at maximum int i, j, k; int invalidDivision = 0; for (i = 0; i < N; i++) { for (j = 1; j <= n; j++) { if (a[j][j] == 0) { invalidDivision = 1; break; } // Initialize before starting values[j - 1] = 0; for (k = 1; k <= n; k++) { double multi = values[k - 1]; if (k == j) multi = 0; // Since j starts from 1 // The sign will be flipped when moving to the right side //printf("values[%d]: %f += %f * %f\n", j - 1, values[j - 1], -(a[j][k] / a[j][j]), multi); values[j - 1] += -(a[j][k] / a[j][j]) * multi; } if (a[j][j] == 0) break; //printf("values[%d] = %f (%f += %f)\n", j - 1, values[j - 1] + a[j][n + 1] / a[j][j], values[j - 1], a[j][n + 1] / a[j][j]); // Add the integer (= Matrix "b") values[j - 1] += a[j][n + 1] / a[j][j]; } if (invalidDivision == 1) break; // After the whole matrix has been processed, check if the result // was accurate enough. double d = findMaxDelta(values, prev_values); printf("d: %f\n", d); // Stop when it becomes accurate enough if (d <= epsilon) { printValues(values); return 0; } // Now, make a backup of the current values (so that we can // calculate the delta in the next loop copyValues(values, prev_values); } // If the program comes out of this loop, it means that N trials were done // but the solutions didn't get accurate enough. swapRow(rowToSwap, rowToSwap2); //printf("swapped %d <=> %d\n", rowToSwap, rowToSwap2); } } } // Coming here means there were many attempts of estimating the solution // but all the attempts ended up not being accurate enough. It is possible // that the epsilon is too small or maybe there's something wrong with the // equation. printf("The equation set is likely it does not converge.\n"); /* プログラムの終了 */ return 0; }
/* * 行最简式,Error */ Matrix* calc_rref(Matrix* p) { Matrix *oldAns = ans; int i, j, k; int l = 0; if (p == NULL) { //Error return NULL; } ans = NULL; if (!stor_createAns(p->m, p->n)) { //Error return NULL; } if (!stor_assign(ans, p)) { //Error return NULL; } if (!ans) { //Error return NULL; } for (i = 0; i < ans->m; i++) { k = isZeroLine(ans, i); if (k == -1) { continue; } if (util_isZero(*stor_entry(ans, i, k))) { //Error return NULL; } mulRow(ans, i, (double)1.0 / *stor_entry(ans, i, k)); if (!ans) { //Error return NULL; } for (j = 0; j < ans->m; j++) { if (i != j && !util_isZero(*stor_entry(ans, j, k))) { addRow(ans, j, i, -*stor_entry(ans, j, k)); } } } l = 0; for (i = 0; i < p->n; i++) { for (j = i; j < p->m; j++) { if (!util_isZero(*stor_entry(ans, j, i))) break; } if (j < p->m) { if (i != j) swapRow(ans, l, j); l++; } } stor_freeMatrix(oldAns); return ans; }
void rotateMatrix(int (*matrix)[4], int n) { invert(matrix, 4); swapRow(matrix, 0, 3, 4); swapRow(matrix, 1, 2, 4); }