0

I have a multidimensional numpy array which I need to modify such that its elements are modified as a function of the index of one of the dimensions only. I can of course do that with a for loop, as in the following simplified example

import numpy as np
a = np.ones( (2,10) )
for ii in range(a.shape[1]):
    a[:,ii] *= ii

If the array becomes very large, this might slow down the execution and I was wondering if there are some clever ways to avoid using a for loop?

1 Answer 1

1

Construct another array to hold the scaling factors, then broadcast and multiply:

scale = np.arange(a.shape[1])
a *= scale
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.