有没有更好的方法使用Eigen / C ++来实现matlab的逻辑索引?

时间:2019-11-26 22:54:53

标签: c++ arrays matlab slice eigen3

我一直在寻找一种更“本征”的方式来实现Matlab的逻辑索引功能。这是我能想到的最好的方法。 (这里为简单起见,将焦点放在int数组上)

//an attempt at matlab-style Logical Indexing
//equivalent to the matlab:
//  original = [1,2,3,4]
//  subset = original(original < 3)

using namespace Eigen;
using std::cout;
using std::endl;

IOFormat OctaveFmt(StreamPrecision, 0, ", ", " ", "", "", "[", "]");

ArrayXi original(4);
original << 1,2,3,4;
cout<<"Original with bad values:"<<endl
    <<original.format(OctaveFmt)<<endl;

Array<bool, Dynamic,1> selections = original < 3;
cout<<"One if it's a good value:"<<endl
    <<selections.format(OctaveFmt)<<endl;

std::vector<int> picked;
for(int i = 0; i < selections.size(); i++ )
{
    if(selections(i))
    {
        picked.push_back(original(i));
    }
}

//put the vector values back into an eigen array
ArrayXi theGoodStuff = Map<ArrayXi, Unaligned>
                       (picked.data(), picked.size());

cout<<"Just the good stuff:"<<endl
    <<theGoodStuff.format(OctaveFmt)<<endl;

这是我得到的输出:

Original with bad values:
[1  2  3  4]
One if it's a good value:
[1  1  0  0]
Just the good stuff:
[1  2]

有没有人知道如何比循环遍历数组更“本征”的方式,或者只是一种更快的方式?

0 个答案:

没有答案