问题描述
在Eigen中是否可以等效于Matlab中的以下操作?
Is it possible in Eigen to do the equivalent of the following operation in Matlab?
A=rand(10,10);
indices = [2,5,6,8,9];
B=A(indices,indices)
我想要一个子矩阵作为具有给定的非连续索引的原始矩阵的视图.最好的选择是拥有原始矩阵的共享内存视图,这可能吗?
I want to have a submatrix as a view on the original matrix with given, non consecutive indices.The best option would be to have a shared memory view of the original matrix, is this possible?
我已经找到了一个可行但不是很快的方法,因为它涉及到非向量化的for循环:
I've figured out a method that works but is not very fast, since it involves non vectorized for loops:
MatrixXi slice(const MatrixXi &A, const std::set<int> &indices)
{
int n = indices.size();
Eigen::MatrixXi B;
B.setZero(n,n);
std::set<int>::const_iterator iInd1 = indices.begin();
for (int i=0; i<n;++i)
{
std::set<int>::const_iterator iInd2=indices.begin();
for (int j=0; j<n;++j)
{
B(i,j) = A.coeffRef(*iInd1,*iInd2);
++iInd2;
}
++iInd1;
}
return B;
}
如何使其更快?
推荐答案
使矩阵遍历col-major(在Eigen中为默认值) http://eigen.tuxfamily.org/dox-devel/group__TopicStorageOrders.html
Make your matrix traversal col-major (which is default in Eigen) http://eigen.tuxfamily.org/dox-devel/group__TopicStorageOrders.html
禁用调试断言,EIGEN_NO_DEBUG
,请参见 http://eigen.tuxfamily.org/dox /TopicPreprocessorDirectives.html ,这是Deepfreeze的建议.
Disable debug asserts, EIGEN_NO_DEBUG
, see http://eigen.tuxfamily.org/dox/TopicPreprocessorDirectives.html, as the comment by Deepfreeze suggested.
实现向量化版本非常简单,因为元素通常不是连续的.如果愿意,请查看AVX2收集说明(前提是您具有支持AVX2的CPU)
It is very non-trivial to implement vectorized version since elements are not contiguous in general. If you are up to it, take a look at AVX2 gather instructions (provided you have CPU with AVX2 support)
要实现矩阵视图(您称为共享内存),您需要实现一个Eigen表达式,如果您精通C ++并且知道Eigen代码库,这并不是很难.如果您愿意,我可以帮助您入门.
To implement matrix view (you called it shared-memory) you'd need to implement an Eigen expression, which is not too hard if you are well versed in C++ and know Eigen codebase. I can help you to get started if you so want.
这篇关于本征索引中的子矩阵视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!