3

I have this piece of Python code that fills up a 2d matrix in a for loop

img=zeros((len(bins_x),len(bins_y)))

for i in arange(0,len(ix)):
   img[ix[i]][iy[i]]=dummy[i]

Is it possible to use a vectorial operation for the last two lines of code? Is there also something that might speed up the calculation?

3
  • Can you post some sample contents of ix, iy, dummy, bins_x, bins_y? Commented Aug 20, 2012 at 15:33
  • This is not really an answer (that's why it's a comment) but while someone comes up with something more "decent", you may want to take a look to the itertools module (docs.python.org/library/itertools.html) See if there's something interesting for you there :) Commented Aug 20, 2012 at 15:40
  • as far as speeding it up, img[ix[i], iy[i] ] = dummy[i] is likely to be faster as it only need to do indexing once instead of twice. Also note that you can pretty this up a little by for x,y,z in zip(ix,iy,dummy): img[x,y] = z, but I don't know if that will be faster. Commented Aug 20, 2012 at 15:46

2 Answers 2

2

If ix, iy are index sequences:

img[ix, iy] = dummy
Sign up to request clarification or add additional context in comments.

6 Comments

I just discovered this about 3 seconds ago. (+1)
Although, technically, you might want to slice them in case they're not the same length: img[ix, iy[:len(ix)] ] = dummy[:len(ix)]
As @mgilson pointed out, you may want to make sure that ix, iy and dummy have all the same size beforehand...
Is this possible with python 2.7? I keep getting TypeError: list indices must be integers, not tuple.
@Kevin: the OP likely uses numpy.zeros() function that returns a numpy array that supports ix,iy indexing.
|
0

It might be useful to use numpy. In particular, the reshape method might be useful. Here is an example (adapted from the second link):

>>> import numpy as np
>>> a = np.array([1,2,3,4,5,6])
>>> np.reshape(a, (3,2))
array([[1, 2],
       [3, 4],
       [5, 6]])

Comments

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.