资源简介
实现任意多个变量以最小二乘法拟合成的新线性方程,通过变量带入线性方程可求得任意的拟合值。文件首行为行号、列号,其余行为数据行。
代码片段和文件信息
#include
#include
#include
using namespace std;
void transpose(double **p1double **p2int mint n);
void multipl(double **p1double **p2double **p3int mint nint p);
void Inver(double **p1double **p2int n);
double SD(double **p1double **p2double **p3double **p4int mint n);
double ST(double **p1int m);
void de_allocate(double **dataint m);
int main() {
int rowcol;
char filename[30];
double SDsumSTsumFR2;
cout<<“Input original data file: \n“;
ifstream infile; //打开文件
cin>>filename;
infile.open(filename);
if(!infile) {
cout<<“Opening the file failed!\n“;
exit(1);
}
infile>>row>>col; //读入文件中的行数和列数
double **matrix=new double*[row]; //为动态二维数组分配内存
double **X=new double*[row];
double **Y=new double*[row];
double **XT=new double*[col];
double **XTX=new double*[col];
double **XTXInv=new double*[col];
double **XTXInvXT=new double*[col];
double **B=new double*[col];
double **YE=new double*[row];
for(int i=0;i
matrix[i]=new double[col];
X[i]=new double[col];
Y[i]=new double[1];
Y[i]=new double[1];
YE[i]=new double[1];
}
for(int i=0;i XT[i]=new double[row];
XTX[i]=new double[2*col];/////////////////////为什么必须分配2*col列空间而不是col?在矩阵求逆时,XTX变增广矩阵,列数变为原来2吧倍,跟求逆算法有关。
XTXInv[i]=new double[col];
XTXInvXT[i]=new double[row];
B[i]=new double[1];
}
for(int i=0;i
for(int j=0;j infile>>matrix[i][j];
infile.close();
for(int i=0;i
X[i][0]=1;
Y[i][0]=matrix[i][col-1];
for(int j=0;j X[i][j+1]=matrix[i][j];
}
transpose(XXTrowcol);
multipl(XTXXTXcolrowcol);
Inver(XTXXTXInvcol);
multipl(XTXInvXTXTXInvXTcolcolrow);
multipl(XTXInvXTYBcolrow1);
SDsum=SD(YXBYErowcol);
STsum=ST(Yrow);
F=((STsum-SDsum)/(col-1))/(SDsum/(row-col));
R2=1/(1+(row-col)/F/(col-1));
cout<<“输出B:\n“; //屏幕输出结果B,SD,ST,F,R2
for(int i=0;i cout< cout< cout<<“SD=“<
ofstream outfile; // 结果写入文件
cout<<“Output file‘name:\n“;
cin>>filename;
outfile.open(filename);
if(!outfile) {
cout<<“Opening the file failed!\n“;
exit(1);
}
outfile<<“输出B:\n“;
for(int i=0;i outfile< outfile< outfile< o
评论
共有 条评论