C++ Eigen3基本使用方法

基本矩阵的构建与矩阵与列向量的乘法计算

#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;
}

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值