MATLAB find()/ Nigen非零成语为Eigen [英] MATLAB find() / Numpy nonzero idioms for Eigen

查看:186
本文介绍了MATLAB find()/ Nigen非零成语为Eigen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很可能这是一个非常愚蠢的问题,但我花了相当荒谬的时间寻找它的文档,没有效果。

Chances are this is a very stupid question but I spent a pretty absurd amount of time looking for it on the documentation, to no avail.

在MATLAB中, find()函数给我一个非零元素的索引数组。 Numpy的np.nonzero函数做类似的事情。

in MATLAB, the find() function gives me an array with the indices of nonzero elements. Numpy's np.nonzero function does something similar.

如何在C ++ Eigen库中做这个?我有一个布尔数组

How do I do this in the C++ Eigen library? I have a Boolean array of

typedef <bool, 10, 1> foobar = MatrixA < MatrixB;

到目前为止。谢谢!

推荐答案

期望Eigen有一个find()函数是合理的。不幸的是,Eigen没有一个,或者甚至小于矩阵的运算符。幸运的是,问题不是太难。这里是这个问题的一个解决方案。我使用向量来存储元素> 0的列主要索引。如果你喜欢,你可以使用VectorXf。在B - A(B-A> 0与评估B> A相同)上使用此方法。我使用stl for_each()函数。

It is reasonable to expect Eigen to have a find() function. Unfortunately, Eigen doesn't have one, or even a less than operator for matrices. Fortunately, the problem isn't too difficult. Here is one solution to the problem. I am using vector to store the Column Major indices of elements > 0. You could use VectorXf if you prefer that. Use this on B - A (B-A > 0 is the same as evaluating B>A). I'm using the stl for_each() function.

#include<algorithm>
#include<vector>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;

class isGreater{
    public:
    vector<int>* GT;
    isGreater(vector<int> *g){GT = g;}
    void operator()(float i){static int it = 0; if(i>0)GT->push_back(it); it++;}
};
int main(int argc,char **argv){
    MatrixXf P = MatrixXf::Random(4,5);
    vector<int> GT;
    for_each(P.data(),P.data()+P.rows()*P.cols(),isGreater(&GT));
    cout<<P<<endl;
    for(int i=0;i<GT.size();++i)cout<<GT[i]<<" ";
    cout<<GT.size()<<endl;
    return 0;
}

这篇关于MATLAB find()/ Nigen非零成语为Eigen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆