我们在求解矩阵时,有很多种方法,其中当矩阵是大型稀疏矩阵(矩阵中有大部分元素都为0)时,我们可以用迭代法求解。
关于该方法的思想和定义,请参考如下博客:
http://www.doc88.com/p-6953977164202.html
我编写的C++代码,也是根据上面的博客中的数学公式。
在这里我们使用的数据文件matrix.txt为
- 第一行表示矩阵的行数或者列数
- 接下来的三行,表示矩阵本体 A
- 最后一行表示 b,A*x=b
- 我们要计算的就是x
3
8 -3 2
4 11 -1
6 3 12
20 33 36
代码如下:
#include <iostream>
#include <fstream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/photo.hpp>
using namespace std;
using namespace cv;
int main()
{
ifstream file("matrix.txt");
int rows;
int cols;
file >> rows;
cols = rows;
Mat A(rows, cols, CV_32FC1);
/*我们假设输入的矩阵对角线元素不为0*/
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
file >> A.at<float>(i, j);
}
}
Mat b(1, cols, CV_32FC1);
for (int i = 0; i < cols; i++)
{
file >> b.at<float>(i);
}
file.close();
//迭代次数 iter = 10次
Mat x(1, cols, CV_32FC1);
x.setTo(0);
for (int iter = 0; iter < 10; iter++)
{
for (int i = 0; i < rows; i++)
{
float sum = 0;
for (int j = 0; j < cols; j++)
{
if (i == j)continue;
sum += A.at<float>(i, j)*x.at<float>(j);
}
x.at<float>(i) = (b.at<float>(i) -sum) / A.at<float>(i, i);
}
}
cout << "最终的结果为:" << endl;
for (int i = 0; i < cols; i++)
{
cout << "x" << i << "=" << x.at<float>(i) << "\t";
}
return 0;
}
最后输出的结果为
最终结果为
x0=3 x1=2 x2=1
和正确的结果一样。在这里我们迭代了10次,求出了最终的结果。关于数值分析,我并没有投入太多的精力,如果有问题和值得改进的地方,希望各位留言。