python - How to fill a numpy array with a gradient with a vectorized code? -


two numpy arrays have filled follow:

[0 1 2]  [0 1 2]  [0 1 2]  [0 1 2]  [0 1 2]]  [[0 0 0]  [1 1 1]  [2 2 2]  [3 3 3]  [4 4 4]] 

or enter image description here

a first idea was:

ax=np.zeros((5,3),np.int16) ay=np.zeros((5,3),np.int16)  j in range(0,3):     in range(0,5):         ax[i,j]=j#filling ax x=col         ay[i,j]=i#filling ay y values y=li 

a second idea was:

bx = np.zeros((5,3),np.int16) = np.zeros((5,3),np.int16)  j in range(3):     bx[:,j]=j  in range(5):     by[i,:]=i 

i sure there's better way, one? jp

i think using numpy.tile might better:

in [422]: np.tile((0,1,2), (5,1)) out[422]:  array([[0, 1, 2],        [0, 1, 2],        [0, 1, 2],        [0, 1, 2],        [0, 1, 2]])  in [473]: tile(arange(5)[:,none], 3) out[473]:  array([[0, 0, 0],        [1, 1, 1],        [2, 2, 2],        [3, 3, 3],        [4, 4, 4]]) 

time efficiency:

for small matrix of shape (5,3), for-loop faster:

in [490]: timeit np.tile((0,1,2), (5,1)) 10000 loops, best of 3: 38.3 per loop  in [491]: %%timeit      ...: bx = np.zeros((5,3),np.int16)      ...: j in range(3):      ...:     bx[:,j]=j      ...:  100000 loops, best of 3: 16.5 per loop 

but large matrix of shape (5, 1000), tile faster:

in [488]: timeit n=1000; tile(xrange(n), (5,1)) 1000 loops, best of 3: 313 per loop  in [489]: %%timeit      ...: n=1000      ...: bx=zeros((5, n))      ...: j in range(n):      ...:     bx[:,j]=j      ...:  100 loops, best of 3: 3.97 ms per loop 

anyway, tile makes code cleaner.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -