有没有更好的方法可以使用特征/C++实现 matlab 的逻辑索引?

Is there a better way to implement matlab's Logical Indexing using Eigen/C++?

本文关键字:matlab 实现 索引 C++ 方法 更好 可以使 特征 有没有      更新时间:2023-10-16

我一直在寻找一种更"特征"的方式来实现 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]

有谁知道如何以更"特征"的方式做到这一点,或者只是比循环遍历数组更快的方式?

这是一个旧的,但是....Eigen 3.4 使此操作更加干净。可悲的是,我无法与表演交谈。我主要对可读性感兴趣。我做了这个:

class logical
{
private:
const Index new_size;
Array<Index, Dynamic, 1> old_inds;
public:
logical(const Array<bool, Dynamic, 1> &keep) : new_size(keep.count()), old_inds(new_size)
{
for (Index i = 0, j = 0; i < keep.size(); i++)
if (keep(i))
old_inds(j++) = i;
}
Index size() const { return new_size; }
Index operator[](Index new_ind) const { return old_inds(new_ind); }
};

其用法如下:

logical inds(ind_to_keep);
Y_slice = Y(inds); // vector
H_slice = H(inds, all); // remove some rows
R_slice = R(inds, inds); // remove the same rows as columns

特征帮助位于本页底部: https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html