Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find ordered vector in numpy array

I need to find a vector in a numpy.array. For example, I have a np.array named e and I want to find the vector [1, 2] in e (meaning that I would like to have the index of the vector inside the matrix) but apparently my programm see the vector even when is not present:

enter image description here

The code I use to built e in the following:

import numpy as np
faces = np.array([[1,2,3,4],[5,6,2,1],[6,7,3,2],[7,8,4,3],[8,5,1,4],[8,7,6,5]])
e = np.zeros([6,4,2])
for k in range(len(faces)):
    a = [faces[k][0], faces[k][1]]
    b = [faces[k][1], faces[k][2]] 
    c = [faces[k][2], faces[k][3]]
    d = [faces[k][3], faces[k][0]]
    e[k] = np.array([a,b,c,d])
 print('e: %s' %e)

any clue how to solve this?

like image 667
JAWE Avatar asked Oct 07 '13 15:10

JAWE


1 Answers

Don't use Python in with numpy arrays.

There are 6 x 4 pairs in e.

In [32]: e.shape
Out[32]: (6, 4, 2)

You are looking an element that matches both (i.e., all()) entries in the pair [1, 2].

In [33]: (e == np.array([1, 2])).all(-1)
Out[33]: 
array([[ True, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)

The -1 in all(-1) refers the last dimension in the array, the part of the shape that constitutes pairs. Using -1 is probably more general than using 2, which would also work in this case.

It found the right match -- the only True value. You can see the shape of this result makes sense.

In [34]: (e == np.array([1, 2])).all(-1).shape
Out[34]: (6, 4)

To get the index of the first match you could do

x, y = (e == np.array([1, 2])).all(-1).argmax(1).argmax(), (e == np.array([1, 2])).all(-1).argmax(0).argmax()

but using np.argwhere suggested in CT Zhu's answer is definitely better.

like image 122
Dan Allan Avatar answered Sep 27 '22 22:09

Dan Allan