[Numpy-discussion] Want to eliminate direct for-loop

Dinesh B Vadhia dineshbvadhia@hotmail....
Sat Feb 11 18:04:20 CST 2012


Sorry, I copy and pasted the wrong example r result - it should be as you say:
r = array([  1,   1,   1,  48,  68,   1,  75,   1,   1, 115,   1,  95,   1,   1,   1,   1,   1,   1,   1,  28,   1,  68,   1,   1,  28])

The reason for looking for an alternative solution is performance as the sizes of r, s and c are very large with the for-loop calculation repeated continuously (with different r, s and c).  




From: eat 
Sent: Saturday, February 11, 2012 3:12 PM
To: Discussion of Numerical Python 
Subject: Re: [Numpy-discussion] Want to eliminate direct for-loop


Hi,


On Sat, Feb 11, 2012 at 10:56 PM, Dinesh B Vadhia <dineshbvadhia@hotmail.com> wrote:

  Could the following be written without the direct for-loop?

  import numpy
  # numpy vector r of any data type and length, eg.
  r = numpy.ones(25, dtype='int') 
  # s is a list of values (of any data type), eg.
  s = [47, 27, 67]
  # c is a list of (variable length) lists where the sub-list elements are index values of r and len(s) = len(c), eg.
  c = [[3, 6, 9], [6, 11, 19, 24], [4, 9, 11, 21 ]]
  # for each element in each sub-list c, add corresponding s value to the index value in r, eg.
  for i, j in enumerate(c):
      r[j] += s[i]

  So, we get:
  r[[3, 6, 9]] += s[0] = 1 + 47 = 48
  r[[6, 11, 19, 24]] += s[1] = 1 + 27 = 28
  r[[4, 9, 11, 21]] += s[2] = 1 + 67 = 68

  ie. r = array([  1,   1,   1,  95,  68,   1, 122,   1,   1, 162,   1,  95,   1,  1,   1,   1,   1,   1,   1,  28,   1,  68,   1,   1,  28])

  Thank-you!
Could you describe more detailed manner about why you want to get rid of that loop? Performance wise? If so, do you have profiled what's the bottleneck?


Please provide also a more detailed description of your problem, since now your current spec seems to yield:
r= array([  1,   1,   1,  48,  68,   1,  75,   1,   1, 115,   1,  95,   1,
            1,   1,   1,   1,   1,   1,  28,   1,  68,   1,   1,  28])




My 2 cents,
-eat



  _______________________________________________
  NumPy-Discussion mailing list
  NumPy-Discussion@scipy.org
  http://mail.scipy.org/mailman/listinfo/numpy-discussion


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120211/b6f2ee39/attachment.html 


More information about the NumPy-Discussion mailing list