使用csparse求解一个简单的稀疏线性方程组:cs_cholsol
Solving a simple sparse linear system of equation using csparse: cs_cholsol
我在Windows 7 x64上使用Microsoft Visual Studio 2008。我试图用csparse求解下面的线性系统Ax=b
,其中A
是正定的。
| 1 0 0 1 |
A = | 0 3 1 0 |
| 0 1 2 1 |
| 1 0 1 2 |
| 1 |
b = | 1 |
| 1 |
| 1 |
我使用了以下代码
int Ncols = 4, Nrows = 4, nnz = 10;
int cols[] = {0, 3, 1, 2, 1, 2, 3, 0, 2, 3};
int rows[] = {0, 0, 1, 1, 2, 2, 2, 3, 3, 3};
double vals[] = {1, 1, 3, 1, 1, 2, 1, 1, 1, 2};
cs *Operator = cs_spalloc(Ncols,Nrows,nnz,1,1);
int j;
for(j = 0; j < nnz; j++)
{
Operator->i[j] = rows[j];
Operator->p[j] = cols[j];
Operator->x[j] = vals[j];
Operator->nz++;
}
for(j = 0; j < nnz; j++)
cout << Operator->i[j] << " " << Operator->p[j] << " " << Operator->x[j] << endl;
Operator = cs_compress(Operator);
for(j = 0; j < nnz; j++)
cout << Operator->i[j] << " " << Operator->p[j] << " " << Operator->x[j] << endl;
// Right hand side
double b[] = {1, 1, 1, 1};
// Solving Ax = b
int status = cs_cholsol(0, Operator, &b[0]); // status = 0 means error.
为了确保我正确地创建了稀疏变量,我尝试在cs_compress
之前和之后将行和列索引及其值打印到控制台。以下是打印输出的结果。
之前:
0 0 1
0 3 1
1 1 3
1 2 1
2 1 1
2 2 2
2 3 1
3 0 1
3 2 1
3 3 2
之后:
0 0 1
3 2 1
1 4 3
2 7 1
1 10 1
2 -6076574517017313795 2
3 -6076574518398440533 1
0 -76843842582893653 1
2 0 1
3 0 2
由于调用cs_compress
后可以观察到上面的垃圾值,Ax=b
的解与我用MATLAB计算的解不匹配。MATLAB得出以下解决方案。
| 2.0000 |
x = | 0.0000 |
| 1.0000 |
|-1.0000 |
有趣的是,对于以下求解Ax=b
的代码,我没有这个问题,其中A
是3×3
的单位矩阵。
int Ncols = 3, Nrows = 3, nnz = Nrows;
cs *Operator = cs_spalloc(Ncols,Nrows,nnz,1,1);
int j;
for(j = 0; j < nnz; j++) {
Operator->i[j] = j;
Operator->p[j] = j;
Operator->x[j] = 1.0;
Operator->nz++;
}
Operator = cs_compress(Operator);
double b[] = {1, 2, 3};
int status = cs_cholsol(0, Operator, &b[0]); // status = 1 means no error.
有人能帮我解决cs_compress
的问题吗?
以前从未使用过csparse,我浏览了源代码。
当您调用cs_spalloc()
来创建Operator
时,您正在创建一个三元组(通过将最后一个参数设置为1
来指示)。但是,在调用cs_copmress()
之后,结果不再是三元组(您可以通过检查结果来检测这一点,并看到压缩后的Operator->n
现在是-1
)。所以,把矩阵当作遍历矩阵是一个错误。
您可以使用cs_print()
API来打印稀疏矩阵。
顺便说一句,您的代码会泄漏内存,因为压缩矩阵是一个新的分配,而cs_compress()
并没有释放原始的未压缩矩阵。
相关文章:
- 向量上的线性搜索
- 二叉搜索如何比线性搜索更快?
- 线性丢番图方程 - 求给定区间内的解数和解
- 查找自动生成键并具有线性内存消耗的小型关联数组
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 线性优化目标函数中的绝对值
- 犰狳C++:带有模量计算的线性组合
- C++(线性搜索和排序)
- 一般采用可索引/可调用的线性组合
- C++线性搜索算法,确定数组中元素的数量
- 使用本征求解线性方程组
- 在C++求解线性方程组的程序
- 在c++中找到一个线性方程组的最优解
- 线性方程组,带约束的最小二乘法
- 使用 Lapack 的 dgesv 求解线性方程组
- 我可以使用本征求解 xA=b 形式的线性方程组,其中 A 是稀疏的
- 使用csparse求解一个简单的稀疏线性方程组:cs_cholsol
- 用C++求解线性丢番图方程组
- 模板化线性方程组求解器,C++
- 求解具有三对角矩阵的线性方程组的库