0

I have started to remove more and more of my for loops by using numpy array operations instead. I am however stuck on the following case. Any help welcome.

I start with a single known value (0.55) in an array A of length L and another array B of length L as well. I want to populate the remaining values in the first array using cross multiplication.

This gives me the desired output:

def cross_mult(B, starting_A = 0.55):
    A= np.zeros(B.shape)
    A[0] = starting_A   
    for i in range(B.shape[0])[1:]:
        A[i] = A[i-1] * B[i] / B[i-1]
    return A

This attempt without the for loop fails:

def cross_mult(B, starting_A = 0.55):
    A= np.zeros(B.shape)
    A[0] = starting_A 
    A[1:] = A[:-1] * B[1:] / B[:-1]
    return A

I get:

array([0.55      , 0.60401715, 0.       ])

Instead of a fully populated array with the three values in it.

0

1 Answer 1

1

The issue with vectorizing this function is that the calculation at each index actually does depend on the index before it, so it's necessary for the calculations to happen sequentially.

To my knowledge, you're stuck using a loop in this situation :)

If you really want to avoid using a loop explicitly though, you can use accumulate:

def cross_mult(B, starting_A = 0.55):
    A= np.zeros(B.shape)
    A[0] = starting_A 
    A[1:] = B[1:] / B[:-1]
    return np.multiply.accumulate(A)
Sign up to request clarification or add additional context in comments.

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.