前言
计算摄影学第三周,课上内容讲了稀疏矩阵及其对应的高斯塞达尔迭代法。课后作业要求写一个并且利用到该迭代法。一开始觉得应该蛮简单的,结果真正写起来又遇阻。。。最后糊里糊涂写了300多行。现在展示出部分重要函数代码,希望对学弟学妹们有所帮助。
稀疏矩阵部分
//节点定义 class Node//节点 {
public: int i;//row of matrix int j;//col of matrix T v;//element value Node* right;//右节点 Node* down;//下节点 Node(int i,int j,T v) {
this->i = i; this->j = j; this->v = v; this->right = nullptr;//不用Null会报错 this->down = nullptr; } Node()//初始化 {
this->i = 0; this->j = 0; this->v = 0; this->right = nullptr; this->down = nullptr; } };
讯享网
讯享网//得到矩阵具体位置的元素 template<class T> T at(int i, int j) {
if (i < 0 || i >= this->row || j < 0 || j >= this->col) {
cout << "out of range" << endl; return 0; } Node<T>* line = &data[i]; Node<T>* elem = getElementofLine(line, j); if(elem == nullptr){
return 0; } return elem->v; }
//Initialize the matrix with 3 vectors void initializeFromVector(vector<int> rows, vector<int> cols, vector<T> vals) {
auto maxrow = max_element(rows.begin(), rows.end()); auto maxcol = max_element(cols.begin(), cols.end()); int size = *maxrow; int newrow = *maxrow + 1; int newcol = *maxcol + 1; Initialize(newrow, newcol);//initialize the matrix for(int i = 0; i < rows.size(); i++){
int ti = rows[i]; int tj = cols[i]; T value = vals[i]; insert(value, ti, tj);//构建矩阵 } }
高斯赛达尔迭代法
讯享网void Gauss_Seidel(double B[], double X[]) {
int i,j,k; double **m = new double*[row]; for(i = 0; i < row; i++) m[i] = new double[col]; int n = this->col; for(i = 0; i < this->row; i++){
for(j = 0; j < this->col; j++){
m[i][j] = at(i, j); } } for(k = 0; k < 1000; k++){
for(i = 0; i < n; i++) {
double sum = 0; for(j = 0; j < n; j++) {
if(j == i) continue;//跳过aii sum += m[i][j] * X[j]; } X[i] = (n[i] - sum) / m[i][i];//替换 x[i] } } }
鸣谢
在本次实验中,高斯赛达尔迭代法矩阵部分由于上课肝大程,没有听明白。。。课后参考了github中@Shuaiqi Ge的代码部分,最后成功写出。此外,稀疏矩阵部分的实现原理也受到了CSDN上@Hober_yao前辈写的文章的启发。在此对两位予以衷心的感谢。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/112331.html