//打印矩阵 template<typename T> voidprint_mat(T* matrix, int row, int col) { for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) cout << std::left << setw(9) << matrix[i * col + j] << " ";
cout << endl; } cout << endl; }
//打印向量 template<typename T> voidprint_vec(T* vector, int len) { for (int i = 0; i < len; ++i) cout << vector[i] << endl; cout << endl; }
//打印增广矩阵 template<typename T, typename I> voidprint_matrix_vec(T* matrix, int row, int col, I* vector, int len) { for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) cout << std::left << setw(9) << matrix[i * col + j] << " "; cout << vector[i] << ends; cout << endl; } cout << endl; }
//交换两行 template<typename T> voidswap_row(T* matrix, int row, int col, int source_row, int dest_row) { //source_row与dest_row交换 //cout << "第 " << source_row << " 行与第 " << dest_row << " 行互换"; T temp_val = 0; for (int i = 0; i < col; ++i) { temp_val = matrix[(dest_row - 1) * col + i]; matrix[(dest_row - 1) * col + i] = matrix[(source_row - 1) * col + i]; matrix[(source_row - 1) * col + i] = temp_val; } cout << endl; }
//交换AX=b中向量 b 的元素 template<typename T> voidswap_vect_row(T* vector, int len, int source_row, int dest_row) { T temp_val = 0; temp_val = vector[dest_row - 1]; vector[dest_row - 1] = vector[source_row - 1]; vector[source_row - 1] = temp_val; }
//某行乘以某数 template<typename T> voidmul_row(T* matrix, int row, int col, int source_row, double multiple) { //cout << "第 " << source_row << " 行乘以 " << multiple <<endl; for (int i = 0; i < col; i++) matrix[(source_row - 1) * col + i] *= multiple; }
template<typename T> voidadd_row(T* matrix, int row, int col, int source_row, int dest_row) { for (int i = 0; i < col; ++i) matrix[(dest_row - 1) * col + i] += matrix[(source_row - 1) * col + i]; }
template<typename T> voidadd_vec_row(T* vector, int len, int source_row, int dest_row) { vector[dest_row - 1] += vector[source_row - 1]; }
template<typename T> voidmul_vec_row(T* vector, int len, int source_row, double mul) { vector[source_row - 1] *= mul; }
//矩阵上三角化 //template<typename T,typename I> voidup_triangle(double* matrix, int row, int col, double* vector, int len)// vector为AX=b中的b { int k = 1; double mul_val = 0; double* temp_array = newdouble[row]; //三角化的过程中是先行再列.. //这里是从矩阵的视角来看的 所以从第1行开始.. for (int j = 1; j < col; ++j) //j为列 { print_matrix_vec((double*)matrix, row, col, vector, len); //打印三角化的过程 //将主元素换到顺序主子式第一行 double max_val = 0.0; int max_row = 0; for (int i = j; i <= row; ++i) //选出在该列中选出最大的行元素作为首元素 { if (fabs(matrix[(i - 1) * col + (j - 1)]) > fabs(max_val)) { max_val = matrix[(i - 1) * col + (j - 1)]; max_row = i; } } swap_row(matrix, row, col, max_row, j); swap_vect_row(vector, len, max_row, j); //print_mat((double*)matrix, row, col);