从Eigen索引的子矩阵视图

时间:2014-12-11 14:36:16

标签: c++ matlab matrix numeric eigen

在Eigen中可以在Matlab中执行以下操作吗?

A=rand(10,10);
indices = [2,5,6,8,9];

B=A(indices,indices)

我希望子矩阵作为原始矩阵的视图,具有给定的非连续索引。 最好的选择是拥有原始矩阵的共享内存视图,这可能吗?

我已经找到了一种有效但速度不快的方法,因为它涉及非向量化for循环:

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

如何更快地完成这项工作?

1 个答案:

答案 0 :(得分:0)

使矩阵遍历col-major(默认为Eigen)http://eigen.tuxfamily.org/dox-devel/group__TopicStorageOrders.html

禁用调试断言EIGEN_NO_DEBUG,请参阅http://eigen.tuxfamily.org/dox/TopicPreprocessorDirectives.html,作为Deepfreeze建议的评论。

实现矢量化版本非常简单,因为元素通常不是连续的。如果您愿意,请查看AVX2收集说明(假设您有支持AVX2的CPU)

要实现矩阵视图(你称之为共享内存),你需要实现一个Eigen表达式,如果你精通C ++并且知道Eigen代码库,那么这个表达式并不难。如果你愿意,我可以帮助你开始。