Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy map calculation depending on the indices

I have a NumPy array of shape (Height, Width). Now I want to calculate the value of all the elements present in this array. The value is a function of the position [x,y] of the element.

Suppose I want to assign all the elements the value as (x**2+y**2)/2. I want to do this without using a for loop. Is there a way to do this?

like image 336
chaithu Avatar asked Oct 17 '25 13:10

chaithu


2 Answers

Must be something like this :

numpy.fromfunction(lambda i, j: (i**2+j**2)/2, (3, 3), dtype=int)

more at : http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html#numpy.fromfunction

like image 61
Louis Avatar answered Oct 20 '25 03:10

Louis


You could also look at meshgrid, mgrid, and/or indices:

>>> H, W = 4,5
>>> x, y = np.indices([H, W])
>>> m
array([[  0. ,   0.5,   2. ,   4.5,   8. ],
       [  0.5,   1. ,   2.5,   5. ,   8.5],
       [  2. ,   2.5,   4. ,   6.5,  10. ],
       [  4.5,   5. ,   6.5,   9. ,  12.5]])

This works because x and y are arrays with the appropriate x and y coordinates:

>>> x
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3]])
>>> y
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])

meshgrid and mgrid allow for finer control, e.g.

>>> x, y = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 10, 3))
>>> x
array([[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
       [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
       [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]])
>>> y
array([[  0.,   0.,   0.,   0.,   0.],
       [  5.,   5.,   5.,   5.,   5.],
       [ 10.,  10.,  10.,  10.,  10.]])
like image 22
DSM Avatar answered Oct 20 '25 04:10

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!