2

I'm trying to figure out how to vectorize the following loop:

for i in range(1,size):
    if a[i] < a[i-1]:
        b[i] = a[i]
    else: b[i] = b[i-1]

b is a (large) array of the same size as a. I could use

numpy.where(a[1:]<a[:-1])

to replace the if statement but how do you simultaneously replace the else statement?

2
  • 1
    I don't think this can be vectorized, since each element depends on the previous one. Commented Dec 18, 2012 at 17:31
  • This is a guess, but the vectorize docs say it the vectorizing function accepts a sequence. Could you rewrite your loop as a generator instead? Commented Dec 18, 2012 at 17:51

2 Answers 2

2

I think you want something like this:

import numpy as np

def foo(a, b):
    # cond is a boolean array marking where the condition is met
    cond = a[1:] < a[:-1]
    cond = np.insert(cond, 0, False)
    # values is an array of the items in from a that will be used to fill b
    values = a[cond]
    values = np.insert(values, 0, b[0])
    # labels is an array of increasing indices into values
    label = cond.cumsum()
    b[:] = values[label]
Sign up to request clarification or add additional context in comments.

2 Comments

This did it thanks. Now to make sure I understand it and then test it for speed.
I hope this gives you some speedup. If you have more information about b, you might be able to get even more of a speedup. For example if you know ahead of time that b should be monotonically increasing.
1

From the docs:

numpy.where(condition[, x, y])

Return elements, either from x or y, depending on condition.

So you can simplify a loop containing:

if cond:
    a[i] = b[i]
else:
    a[i] = c[i]

to

a = numpy.where(cond, a, b)

However, I don't think your example can be vectorized, since each element depends on the previous one.

1 Comment

I think you're right. So what options are there to speed up an operation such as this if vectorizing is not possible?

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.