基本矩阵的构建与矩阵与列向量的乘法计算
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
MatrixXd m = MatrixXd::Random(3, 3); // 创建3*3随机矩阵
cout <<"Matrix m"<< endl;
cout << m << endl;
MatrixXd C = MatrixXd::Constant(3, 3, 1.2); // 创建3*3的值全为1.2的矩阵
cout << "Matirx C" << endl;
cout << C << endl;
m = (m + C) * 50; // 矩阵的加法与数乘
cout << "m =" << endl << m << endl;
VectorXd v(3); // 创建3*1列向量
v << 1, 2, 3; // 读入列向量的值
cout << "vector v" << endl;
cout << v << endl;
cout << "m * v =" << endl << m * v << endl; // 计算矩阵乘法
}
在一些计算机视觉领域,常用的矩阵仅仅是3*3的,这时有更简便方法生成这种矩阵,直接使用Matrix m
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
Matrix3d m = Matrix3d::Random();
cout << "Matrix m" << endl;
cout << m << endl;
m = (m + Matrix3d::Constant(1.2)) * 50;
cout << "m =" << endl << m << endl;
Vector3d v(1, 2, 3);
cout << "m * v =" << endl << m * v << endl;
}
先定义矩阵,在依次对矩阵每个元素进行赋值,是一种常用方法,下面是例子
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
MatrixXd m(2, 2); // 定义一个2*2矩阵
m(0, 0) = 3;
m(1, 0) = 2.5; // 矩阵赋值
m(0, 1) = -1;
m(1, 1) = m(1, 0) + m(0, 1);
cout << "Here is the matrix m:\n" << m << endl;
VectorXd v(2); // 定义一个2*1列向量
v(0) = 4;
v(1) = v(0) - 1; // 列向量赋值
cout << "Here is the vector v:\n" << v << endl;
}