0

If the 3x4 matrix is shown below,

a=[[1,2,3,4], [5,6,7,8], [9,10,11,12]]

I want to find 7 and draw the coordinate value (2,3) into a variable.

Do you have a built-in function?

In matlab, [row, col] = find(a==7), and result is row=2,col=3.

I'm curious about how Python works.

loki
  • 976
  • 1
  • 10
  • 22

3 Answers3

2

After initializing the value of the matrix value you want,

val = 7

here is a nice one-liner:

array = [(ix,iy) for ix, row in enumerate(a) for iy, i in enumerate(row) if i == val]

Output of print(array):

[(1, 2)]

Note the one-liner will catch all instances of the number 7 in a matrix, not just one. Also note the indexes start at 0, so row 2 will be displayed as 1 and column 3 will be displayed as 2. If, say, you have more than one instance of 7 in a row and want the actual row and column numbers (not starting at 0), this may be helpful:

a=[[1,7,7,4], [5,6,7,8], [9,10,11,7]]
val = 7
array = [(ix+1,iy+1) for ix, row in enumerate(a) for iy, i in enumerate(row) if i == val]
print(array)

Output:

[(1, 2), (1, 3), (2, 3), (3, 4)]
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
0

To do it similar to Matlab you would have to use numpy

import numpy as np

a = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

a = np.array(a)

rows, cols = np.where(a == 7)

print(rows[0], cols[0])

It can find all 7 in matrix so it returns rows, cols as lists.

And it counts rows/cols starting at 0 so you may have to add +1 to get the same results as matlab

furas
  • 134,197
  • 12
  • 106
  • 148
  • thank you very much! I wonder why using np.array. Is is different with just python array? –  Jan 13 '20 at 02:39
  • Python is general-purpose language and it has only normal list which doesn't have functions like array in specialized matlab. To do it similar to `matlab` you have to use `numpy`. – furas Jan 13 '20 at 02:43
-1

I would use numpy's where function. Here's another post that displays it's use nicely. I'd apply it to your use case like so:

 import numpy as np

arr = np.array([[1, 2, 3],[4, 100, 6],[100, 8, 9]])
positions = np.where(arr == 100)
# positions = (array([1, 2], dtype=int64), array([1, 0], dtype=int64))
positions = [tuple(cor.item() for cor in pos) for pos in positions]
# positions = [(1, 2), (1, 0)]

Note that this solution allows for the possibly that the desired pattern might occur more than once.