How can I make this code faster (without using a loop)?

Question:

I’m trying to do this to a numpy array x_new in every loop. Is there a way to make it faster?

for i in range(nup):
    for j in range(nup):
        if j==i+1:
            x_new[i]=x_new[i]-U1[i]*x_old[j]
        elif j==i-1:
            x_new[i]=x_new[i]-L1[j]*x_old[j]
        elif j==i+nf:
            x_new[i]=x_new[i]-U2[i]*x_old[j]
        elif j==i-nf:
            x_new[i]=x_new[i]-L2[j]*x_old[j]

                

when nup is big, it takes way too long.

Asked By: Michael

||

Answers:

You can optimize the loop by removing the inner loop and replacing the j values with the expressions used in the conditionals. This way, you directly access the required indices without iterating through all the possible values of j:

for i in range(nup):
    if i + 1 < nup:
        x_new[i] -= U1[i] * x_old[i + 1]
    if i - 1 >= 0:
        x_new[i] -= L1[i - 1] * x_old[i - 1]
    if i + nf < nup:
        x_new[i] -= U2[i] * x_old[i + nf]
    if i - nf >= 0:
        x_new[i] -= L2[i - nf] * x_old[i - nf]

This optimization reduces the time complexity from O(nup^2) to O(nup), which should significantly speed up the loop.

Answered By: Random Davis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.