原本是为了编程实现线性回归的,想想,里面太多矩阵操作,尤其是求逆。以前学数值分析时,也用到过列主元高斯消去求解线性方程组,LU分解求解线性方程组。这次,同样是用高斯消去法求矩阵行列式的值,用LU分解求解矩阵的逆,效率上程序执行起来还行,比用python跑一边速度快,结果一致,这也潜在说明python库中矩阵求逆的实现应该也是用的LU分解。至于矩阵的其他一些操作,基本上算简单,当然面的稀疏性矩阵的话,采用三元组的形式表示,运算起来会更好,但这里不考虑,可以放到数据结构数组的表示方式那一章中。下面给出c++实现的代码
#include <iostream>
#include <stdlib.h>
#include <string>
#include <math.h>
#include "loadData.h"
#include <fstream>
#include <sstream>
#include <stack>
using namespace std;
#define MAX_SIZE_OF_TRAINING_SET 100
#define MAX_NUMIT 100
#define ATTR_NUM 3
#define MAX 1000000
#define MIN -100000
#define MAX_MATRIX_COL 1000
#define MAX_MATRIX_ROW 100
class Matrix
{
public:
double **mat;
int col,row;
public:
int loadMatrix(Matrix *matrix,dataToMatrix dtm)
{
int i,j;
Data *p;
p=dtm.dataSet->next;
matrix->mat=(double **)malloc(sizeof(double*)*dtm.col);
for(i=0; i<dtm.col&&p!=NULL; i++)
{
matrix->mat[i]=(double *)malloc(sizeof(double)*dtm.row);
for(j=0; j<dtm.row; j++)
{
matrix->mat[i][j]=p->attr_double[j];
}
p=p->next;
}
matrix->row=dtm.row;
matrix->col=dtm.col;
return 0;
}
int initMatrix(Matrix *matrix,int col,int row)
{
matrix->col=col;
matrix->row=row;
matrix->mat=(double **)malloc(sizeof(double*)*col);
int i=0,j=0;
for(i=0; i<col; i++)
{
matrix->mat[i]=(double *)malloc(sizeof(double)*row);
for(j=0; j<row; j++)
matrix->mat[i][j]=0;
}
return 0;
}
int initMatrix(Matrix *matrix,int col,int row,double lam)
{
matrix->col=col;
matrix->row=row;
matrix->mat=(double **)malloc(sizeof(double*)*col);
int i=0,j=0;
for(i=0; i<col; i++)
{
matrix->mat[i]=(double *)malloc(sizeof(double)*row);
for(j=0; j<row; j++)
{
matrix->mat[i][j]=0;
if(i==j)
matrix->mat[i][j]=lam;
}
}
return 0;
}

这篇博客主要介绍了使用C++进行矩阵操作,包括利用高斯消去法计算行列式以及通过LU分解求解矩阵逆。作者对比了C++实现与Python库的效率,表明两者结果一致,暗示Python库可能也采用LU分解。文中并未涉及稀疏矩阵的处理,这部分内容将在后续章节讨论。
&spm=1001.2101.3001.5002&articleId=70855474&d=1&t=3&u=c593e24c93114358a23da004c3f01290)
1万+

被折叠的 条评论
为什么被折叠?



