1

Two numpy arrays have to be filled as 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)

for j in range(0,3):
    for i in range(0,5):
        ax[i,j]=j#filling ax with x=col
        ay[i,j]=i#filling ay with y values y=li

A second idea was:

bx = np.zeros((5,3),np.int16)
by = np.zeros((5,3),np.int16)

for j in range(3):
    bx[:,j]=j

for i in range(5):
    by[i,:]=i

I am sure there's a better way, which one? Thanks jp

1 Answer 1

2

I think using numpy.tile might be 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 a small matrix of shape (5,3), the for-loop is faster:

In [490]: timeit np.tile((0,1,2), (5,1))
10000 loops, best of 3: 38.3 us per loop

In [491]: %%timeit
     ...: bx = np.zeros((5,3),np.int16)
     ...: for j in range(3):
     ...:     bx[:,j]=j
     ...: 
100000 loops, best of 3: 16.5 us per loop

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

In [488]: timeit n=1000; tile(xrange(n), (5,1))
1000 loops, best of 3: 313 us per loop

In [489]: %%timeit
     ...: n=1000
     ...: bx=zeros((5, n))
     ...: for j in range(n):
     ...:     bx[:,j]=j
     ...: 
100 loops, best of 3: 3.97 ms per loop

Anyway, tile makes code cleaner.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! How to timeit ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.