I have a 100 by 100 numpy matrix. The matrix is mostly filled with zeros, but also contains some number of ints. For example:
[0 0 0 0 0 0 0 1]
[0 2 2 0 0 0 0 0]
[0 0 2 0 0 0 0 0] False
[0 0 0 0 0 0 0 0]
[0 3 3 0 0 0 0 0]
What is the most efficient way to identify whether the matrix contains any number of adjacent ints of distinct types?
The above example would return False. Here is a True example, with the row containing the adjacency indicated:
[0 0 0 0 0 0 0 1]
[0 2 2 1 1 0 0 0] <---- True
[0 0 2 0 0 0 0 0]
[0 0 0 0 0 0 0 0]
[0 3 3 0 0 0 0 0]
Diagonals do not count as being adjacent. So this example would also return False:
[0 0 0 1 1 1 1 1]
[0 2 2 0 1 0 0 0]
[0 0 2 0 0 0 0 0] False
[0 3 0 0 0 0 0 0]
[3 3 3 0 0 0 0 0]
I do not need to identify the position of the adjacency, just whether it exists of not.
Currently, I cannot do better than finding each no-zero element in the matrix and then checking its 4 flanking elements.
Thanks for all the great answers.
numpy.diffwith an axis parameter is where I would start.