'Logical indexing - numpy.where in C++

I have created a simple numpy array with shape (4, 2) called A.

import numpy as np
A = np.array([[1, 2], 
              [2, 2],  
              [3, 2], 
              [4, 2]]) 

I wanted to get the index of the rows where the first column is 2 and 3, so I did:

indices = np.where((A[:, 0] == 2) | (A[:, 0] == 3))[0]

Doing this I got an array with two items (1 and 2), which is what I wanted.

Now I would like to do this in C++ efficiently. Is there any way to do this using Eigen? I would like to avoid for loops.

Thanks.



Solution 1:[1]

Avoiding for loops in NumPy is admirable. But in fact all you're doing there is pushing the loops down into lower-level code implemented in C or Fortran.

There is simply no need to avoid loops in C++. On the contrary, loops are the clear and obvious way to solve this problem in C++. So use loops. They're blazing fast.

Solution 2:[2]

this is numpy in c++ it is using for loop to do [where]

https://github.com/dpilger26/NumCpp/blob/master/include/NumCpp/Functions/where.hpp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Zwinck
Solution 2 YU Chen Shih