[Eigen]Eigen简易实现matlab中的reshape功能

查看官方文档中,已经有了reshape,reshape是和slicing在一起的。
在这里插入图片描述
Eigen does not expose convenient methods to take slices or to reshape a matrix yet. Nonetheless, such features can easily be emulated using the Map class.
Eigen还没有提供方便使用的方法来进行slicing以及reshape矩阵。尽管如此,使用Eigen中的Map类可以轻松的模拟这些特性。
A reshape operation consists in modifying the sizes of a matrix while keeping the same coefficients. Instead of modifying the input matrix itself, which is not possible for compile-time sizes, the approach consist in creating a different view on the storage using class Map. Here is a typical example creating a 1D linear view of a matrix:
Reshape操作包括修改矩阵的大小,同时保持相同的系数。这种方法不是修改输入矩阵本身(这对于编译时大小是不可能的),而是使用Map类映射在存储上创建一个不同的视图。下面是一个创建矩阵一维线性视图的典型例子:

代码

在vs中新建空项目,然后添加main.cpp
在这里插入图片描述

#include "../Common/common.h"

using namespace Eigen;
using namespace std;
int main()
{
	MatrixXf M1(3, 3);    // Column-major storage
	M1 << 1, 2, 3,
		4, 5, 6,
		7, 8, 9;
	//行向量
	Map<RowVectorXf> v1(M1.data(), M1.size());
	cout << "v1:" << endl << v1 << endl;
	//Eigen::Map方法由一维行向量创建一个一维的矩阵
	Matrix<float, Dynamic, Dynamic, RowMajor> M2(M1);
	Map<RowVectorXf> v2(M2.data(), M2.size());
	cout << "v2:" << endl << v2 << endl;

	MatrixXf M3(2, 6);    // Column-major storage
	M3 << 1, 2, 3, 4, 5, 6,
		7, 8, 9, 10, 11, 12;
	cout << "M3:" << endl << M3 << endl;
	//Eigen::Map方法reshape(M3,[6,2]);
	Map<MatrixXf> M4(M3.data(), 6, 2);
	cout << "M4:" << endl << M4 << endl;
	return 0;
}

Matlab测试样例

M3 = [1, 2, 3,  4,  5,  6;
      7, 8, 9, 10, 11, 12];
M4 = reshape(M3,[6,2]);

运行结果

Eigen运行结果
在这里插入图片描述
matlab的结果
在这里插入图片描述

参考

Eigen这里实现起来还是比较简单的,如果需要大量的数据进行reshape,笔者的思路是从文件来读,可以看笔者的这个博文
Eigen将矩阵写至文件与读文件的简单例子

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值