We define a float matrix 5x5, we will assign two non zero values at two of its components.
Then we discover how to obtain the coordinates (i,j) of the non zero values.
This can be done easily in one line of code.
Library needed: scipy
from scipy import * #this imports all the scipy functions
a=zeros([5,5], float) #an example of matrix
a[1,2]=4
a[4,3]=5
(i,j)=(a>3).nonzero() # where a is greater than 3:
so i and j are the indices of the matrix where a satisfies the condition above:
>>> print i[0]
1
>>> print i[1]
4
>>> print j[0]
2
>>> print j[1]
3
Library needed: scipy
from scipy import * #this imports all the scipy functions
a=zeros([5,5], float) #an example of matrix
a[1,2]=4
a[4,3]=5
(i,j)=(a>3).nonzero() # where a is greater than 3:
so i and j are the indices of the matrix where a satisfies the condition above:
>>> print i[0]
1
>>> print i[1]
4
>>> print j[0]
2
>>> print j[1]
3
For those who know IDL it is easy to see how this Python command is much more flexible then IDL where() function.
Nessun commento:
Posta un commento