c++ - C++ Cholesky 分解
问题描述
我需要使用 C++ 重写一些 MatLab 代码。
在 Matlab 代码中,我们调用该函数chol
来计算上三角矩阵。
对于 C++ 部分,我开始关注 Eigen。但是,我很难获得与 Matlab 的功能等效的chol
功能。
我尝试使用LDLT
Eigen 类:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main() {
MatrixXd matA(2, 2);
matA << 1, 2, 3, 4;
MatrixXd matB(4, 4);
matB << matA, matA/10, matA/10, matA;
matB = matB*matB.transpose();
Eigen::LDLT<MatrixXd> tmp(matB);
MatrixXd U = tmp.matrixU();
cout << U << endl;
}
但结果与 Matlab 代码不同:
matB = [ 1 2 0.1 0.2
3 4 0.3 0.4
0.1 0.2 1 2
0.3 0.4 3 4];
matB = matB*matB';
D = chol(matB);
解决方案
使用您的代码示例和Matlab 文档,我在使用 LLT 而不是 LDLT(在线)时得到相同的结果:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using std::cout;
int main()
{
MatrixXd matA(3,3);
matA << 1, 0, 1, 0, 2, 0, 1, 0, 3;
cout << matA << "\n\n";
Eigen::LDLT<MatrixXd> tmp(matA);
cout << ((tmp.info() == Success) ? "succeeded" : "failed") << "\n\n";
MatrixXd U = tmp.matrixL();
cout << U << "\n\n";
// Using LLT instead
cout << MatrixXd(matA.llt().matrixL()) << "\n\n";
cout << MatrixXd(matA.llt().matrixU()) << "\n\n";
}
输出:
1 0 1
0 2 0
1 0 3成功了
1 0 0
0 1 0
0.333333 0 11 0 0
0 1.41421 0
1 0 1.414211 0 1
0 1.41421 0
0 0 1.41421
推荐阅读
- javascript - 简单的基于文本的游戏更新文本有问题
- machine-learning - 使用 joblib.dump 保存模型文件后,是否可以获得模型中使用的特征/变量列表?
- c# - 如何将表达式树与具有空选项的对象一起应用
- javascript - 使用 CSS 选择器调用 Javascript
- reactjs - 如何使用扩展运算符更新 React js 中的状态?
- sed - 使用具有多个同名键的 sed 替换 yml 文件的内容
- excel - 将 Office.js(Excel 加载项)连接到 SQL Server
- sql - 如何修复与两个条件匹配的记录的此查询?
- php - PHP7 为所有标准 php 函数添加斜线 php-cs-fixer 规则
- php - Eloquent Collection contains() 有效,但 diff() 或 intersect() 认为一切都不一样