Eigen学习笔记Day1

1矩阵初始化以及基本使用

#include <iostream>
#include<Eigen/Dense>//Eigen 头文件 <Eigen/Dense>包含Eigen 里面所有的函数和类
using namespace std;
int main() {
    
    
	Eigen::MatrixXd m(2, 2);// MatrixXd 是动态数组,初始化的时候指定数组的行数和列数
	m(0, 0) = 3;//m(i,j)表示第i行和第j列的值,这里对数组进行初始化
	m(1, 0) = 2.5;
	m(0, 1) = -1;
	m(1, 1) = m(1, 0) + m(0, 1);
	cout << m << endl;//eigen 重载<< 运算符 可以直接输出eigen 矩阵
}

2 矩阵和向量

// 矩阵和向量
#include<iostream>
#include<Eigen/Dense>
using namespace Eigen;
using namespace std;
int main() {
    
    
	MatrixXd m = MatrixXd::Random(3, 3);//初始化动态矩阵m,使用random 函数,初始化的值在[-1,1]区间
	m = (m + MatrixXd::Constant(3, 3, 1.2)) * 50;//MatrixXd::Constant(3, 3, 1.2)初始化3*3的矩阵 元素全部为1.2
	cout << "m=" << endl << m << endl;
	VectorXd v(3);
	v << 1, 2, 3;// 逗号初始化 comma initializer ,Eigen未提供c++ 的{}初始化方式
	cout << "v=" << endl << v << endl;
	cout << "v*m=" << endl << m * v << endl;//
}

3逗号初始化

// 逗号初始化
// Eigen提供了一种逗号初始化器语法,该语法使用户可以轻松设置矩阵,
// 向量或数组的所有系数。只需列出系数,从左上角开始,从左到右,从上到下移动。
// 需要预先指定对象的大小。如果列出的系数太少或太多,编译器就会报错。
//此外,初始化列表的元素本身可以是向量或矩阵。通常的用途是将向量或矩阵连接在一起。
//例如,这是如何将两个行向量连接在一起。请记住,必须先设置大小,然后才能使用逗号初始化程序。
#include<iostream>
#include<Eigen/Dense>
using namespace Eigen;
using namespace std;
int main() {
    
    
	RowVectorXd  cevl(2);
	cevl << 1, 2;
	cout << cevl << endl;
	cout << "----------" << endl;
	RowVectorXd cevl2(3);
	cevl2 << 3, 4, 5;
	RowVectorXd cevl3(5);
	cevl3 << cevl2, cevl;
	cout << cevl3 << endl;
	cout << "----------" << endl;
	MatrixXd m(2, 2);
	m << 1, 2, 3, 4;
	cout << m << endl;
}

4 一些常用的初始化方法

// 一些常用的初始化方法
#include<iostream>
#include<Eigen/Dense>

using namespace std;
using namespace Eigen;

int main() {
    
    
	MatrixXd m0 = MatrixXd::Random(3, 3);// 随机初始化的值在[-1,1]区间内 矩阵大小为3*3
	MatrixXd m1 = MatrixXd::Constant(3, 3, 2.4);//常量值初始化,矩阵的值全部为2.4,3个参数分别代表行数、列数、常量值
	MatrixXd m2 = MatrixXd::Zero(2, 2);// 0矩阵初始化 矩阵的值全部为0
	Matrix4d m3 = Matrix4d::Identity();//初始化单位矩阵
	cout << "m3=" << endl << m3 << endl;
	MatrixXf mat = MatrixXf::Ones(2, 3);
	cout << "before" << endl << mat << endl;
	mat = (MatrixXf(2, 2) << 0, 1, 2, 0).finished() * mat;//此处使用了临时变量,然后使用逗号初始化 在此必须使用finish()方法来获取实际的矩阵对象
	cout << "after" << endl << mat << endl;
}

说明: MatrixXd 是初始化动态矩阵 后面必须说明数组的行数和列数

​ Matrix2d Matrix3d 是显式说明矩阵的维数 不需要进行尺寸说明

参考链接:https://blog.csdn.net/hongge_smile/article/details/107296658

猜你喜欢

转载自blog.csdn.net/weixin_44135909/article/details/121436338