2

I have the following array:

>>> x = numpy.array([2,4,2,3,1])
>>> x
array([2, 4, 2, 3, 1])

I would like an array of ranges of these values. I can create it like this:

>>> numpy.hstack( (numpy.arange(v) for v in x) )
array([0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 2, 0])

Given x, is there a faster way to generate this with numpy without having to use a for loop?

3
  • Looks like you found your solution... It would be interesting to know why you needed this, and why in this particular format. Commented Mar 14, 2011 at 15:09
  • I was working on speeding up the pycollada library (github.com/pycollada/pycollada). One of the geometry types in the collada format is called a polylist and it stores the vertex count of each polygon in an array like the x above. I needed the output range set to triangulate the polygons quickly in a single array. Commented Mar 14, 2011 at 18:58
  • You can see how it works in the triangleset() function I created in this commit: github.com/pycollada/pycollada/commit/… Commented Mar 14, 2011 at 19:00

2 Answers 2

1

I figured it out:

>>> x
array([2, 4, 2, 3, 1])
>>> ends = numpy.cumsum(x)
>>> ranges = numpy.arange(ends[-1])
>>> ranges = ranges - numpy.repeat(ends-x, x)
>>> ranges
array([0, 1, 0, 1, 2, 3, 0, 1, 0, 1, 2, 0])
>>> 
Sign up to request clarification or add additional context in comments.

Comments

0

Is this actually faster ? I have a similar need, and

concatenate([range(l, r) for l, r in array((left, right)).T])

is twice as fast as

range(end[-1]) + repeat(left + end, right-left)

(where end = cumsum(right - left) just like yours).

(in my very short experience, repeat is very slow -- at least in python 3.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.