
Hi guys,
I would like to know if there is any way to make the following operation faster.
def test(): shape=(200,200,200,3) refinds = np.ndindex(shape[:3]) reftmp=np.zeros(shape) for ijk_t in refinds: i,j,k = ijk_t reftmp[i,j,k,0]=i reftmp[i,j,k,1]=j reftmp[i,j,k,2]=k
%timeit test() 1 loops, best of 3: 19.5 s per loop
I am using ndindex and then a for loop. Is there a better/faster way?
Thank you, Eleftherios

On Sat, 04 Dec 2010 19:00:43 +0000, Eleftherios Garyfallidis wrote: [clip]
I am using ndindex and then a for loop. Is there a better/faster way?
Yes:
import numpy as np from numpy import newaxis
x = np.zeros((200, 200, 200, 3)) x[...,0] = np.arange(200)[:,newaxis,newaxis] x[...,1] = np.arange(200)[newaxis,:,newaxis] x[...,2] = np.arange(200)[newaxis,newaxis,:] x[1,3,2] # -> array([ 1., 3., 2.])
Depending on what you use this array for, it's possible that you can avoid constructing it (and use broadcasting etc. instead).

This is beautiful! Thank you Pauli.
On Sat, Dec 4, 2010 at 7:16 PM, Pauli Virtanen pav@iki.fi wrote:
On Sat, 04 Dec 2010 19:00:43 +0000, Eleftherios Garyfallidis wrote: [clip]
I am using ndindex and then a for loop. Is there a better/faster way?
Yes:
import numpy as np from numpy import newaxis
x = np.zeros((200, 200, 200, 3)) x[...,0] = np.arange(200)[:,newaxis,newaxis] x[...,1] = np.arange(200)[newaxis,:,newaxis] x[...,2] = np.arange(200)[newaxis,newaxis,:] x[1,3,2] # -> array([ 1., 3., 2.])
Depending on what you use this array for, it's possible that you can avoid constructing it (and use broadcasting etc. instead).
-- Pauli Virtanen
NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
participants (2)
-
Eleftherios Garyfallidis
-
Pauli Virtanen