[SciPy-user] getting rid of for loops...

LB berthe.loic@gmail....
Thu Aug 2 16:32:18 CDT 2007


Suppose you want to compare two matrices A and B :
>>> A = random.randint(-10, 10, size=(4, 5))
>>> B = random.randint(-10, 10, size=(6, 5))
>>> tollerance = array([10, 15, 5, 8, 6])
>>> A
array([[-7, -2, -5, -1, -2],
       [-9, -9,  9, -9,  1],
       [ 9, -9,  3, -6, -6],
       [-8, -5, -8,  7,  2]])
>>> B
array([[ 8,  2,  2,  4,  3],
       [ 3, -3, -7,  5,  3],
       [-4,  9,  6, -8,  3],
       [ 3, -6,  5, -7, -3],
       [ 3, -5, -3,  1,  5],
       [ 4, -5, -5,  0, -3]])

Use broadcasting to replace for loops :
>>> data1= A[newaxis, :, :]
>>> data1.shape
(1, 4, 5)
>>> data2 = B[:, newaxis, :]
>>> data2.shape
(6, 1, 5)

>>> close_enough = less(abs( data1-data2), tollerance).all(axis=2)
>>> close_enough
array([[False, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, True, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)

So we have a true value on the row 3 and on the column 2 :
>>> less(abs(B[3]-A[2]), tollerance)
array([True, True, True, True, True], dtype=bool)

--
LB



More information about the SciPy-user mailing list