0

I'm using Python 3.8. I'm trying to stop using loops and instead use vectorization to speed up my code. I'm not too sure how to vectorize an equation that uses the result from the step before.

I know how to do basic vectorization like change this:

for i in range(5):
    j=i*2

into this

i=range(5)
j=i*2

but how would I translate something like this, that uses the index from the previous step into a vectorized equation?

j=0
for i in range(1,5):
    k=i*2+j
    j=i
HotFuzz
  • 37
  • 6
  • 1
    You don't. Parallelizing loops that use past results is either impossible or requires a 10+ page long research paper describing a state-of-the-art algorithm on it. – Aplet123 Nov 13 '20 at 02:29

1 Answers1

0

If a value in the vector depends on previous components, this is not possible to fully parallelise. Depending on the particular operation, however, you can make the algorithm a bit more efficient by using other operations in a smart way: For instance, here the cummulative sum is used to make the computation a bit better than a naive for loop. And here you have another alternative (and a benchmark, although it's done in MATLAB)

Mateo Torres
  • 1,545
  • 1
  • 13
  • 22