您的位置:首页 > 编程语言 > C语言/C++

Eigen: C++开源矩阵计算工具——安装与使用

2016-09-18 19:58 691 查看

因为最近在研究卡尔曼滤波,要用到矩阵运算,就想着用C++一次性把矩阵运算写好吧,写一半觉得这么基础的工具应该有人写过吧,发现有很多库!!!


有人做了总结:

C++矩阵运算库推荐 

矩阵运算库Armadillo,Eigen,MATCOM在windows+vs2010环境下的安装和测评

大家用得比较多的是Eigen,Eigen的特点:

(1) 使用方便、无需预编译,调用开销小(2) 函数丰富,风格有点近似MATLAB,易上手;(3) 速度中规中矩,比opencv快,比MKL、openBLAS慢;

Eigen的下载与安装,可参考:C++矩阵处理工具——Eigen
Eigen的简单使用
参考:C++开源矩阵计算工具——Eigen的简单用法(一)C++开源矩阵计算工具——Eigen的简单用法(二)
C++开源矩阵计算工具——Eigen的简单用法(三)
Eigen矩阵运算库使用记录

使用方法很简单:下载Eigen后解压,然后包含解压路径,最后只需要在程序里引用头文件和使用命名空间#include <Eigen/Dense> using namespace Eigen;
矩阵定义
Matrix<double, 3, 3> A;               // Fixed rows and cols. Same as Matrix3d.
Matrix<double, 3, Dynamic> B;         // Fixed rows, dynamic cols.
Matrix<double, Dynamic, Dynamic> C;   // Full dynamic. Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E;     // Row major; default is column-major.
Matrix3f P, Q, R;                     // 3x3 float matrix.
Vector3f x, y, z;                     // 3x1 float matrix.
RowVector3f a, b, c;                  // 1x3 float matrix.
VectorXd v;                           // Dynamic column vector of doubles
基本使用方法
// Eigen          // Matlab           // comments
x.size()          // length(x)        // vector size
C.rows()          // size(C,1)        // number of rows
C.cols()          // size(C,2)        // number of columns
x(i)              // x(i+1)           // Matlab is 1-based
C(i,j)            // C(i+1,j+1)       //

A.resize(4, 4);   // Runtime error if assertions are on.
B.resize(4, 9);   // Runtime error if assertions are on.
A.resize(3, 3);   // Ok; size didn't change.
B.resize(3, 9);   // Ok; only dynamic cols changed.

A << 1, 2, 3,     // Initialize A. The elements can also be
4, 5, 6,     // matrices, which are stacked along cols
7, 8, 9;     // and then the rows are stacked.
B << A, A, A;     // B is three horizontally stacked A's.
A.fill(10);       // Fill A with all 10's.
特殊矩阵生成
// Eigen                            // Matlab
MatrixXd::Identity(rows,cols)       // eye(rows,cols)
C.setIdentity(rows,cols)            // C = eye(rows,cols)
MatrixXd::Zero(rows,cols)           // zeros(rows,cols)
C.setZero(rows,cols)                // C = ones(rows,cols)
MatrixXd::Ones(rows,cols)           // ones(rows,cols)
C.setOnes(rows,cols)                // C = ones(rows,cols)
MatrixXd::Random(rows,cols)         // rand(rows,cols)*2-1    // MatrixXd::Random returns uniform random numbers in (-1, 1).
C.setRandom(rows,cols)              // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high)  // linspace(low,high,size)'
v.setLinSpaced(size,low,high)       // v = linspace(low,high,size)'
矩阵四则运算
// All the same as Matlab, but matlab doesn't have *= style operators.
// Matrix-vector.
y  = M*x;
a  = b*M;
a *= M;

// Matrix-matrix.
R  = P*Q;
R  = P - Q;
R  = P + Q;
R *= Q;
R += Q;
R -= Q;

//Matrix-scalar.
R  = P*s;
R  = s*P;
R  = P/s;
R  = s*P;
R *= s;
R /= s;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: