1

I'm wondering that must be a way of doing the following without the for loop:

import numpy
from itertools import product as itprod

a = np.arange(120.).reshape(3,2,5,2,2)
fact = np.linspace(1,1.4,15).reshape((3,5))

for i,j in itprod(range(3),range(5)):
    a[i,:,j]*= fact[i,j]

Any suggestions??

2
  • Why do you want to avoid a for-loop? Commented Sep 11, 2015 at 15:24
  • 2
    @That1Guy: A Python for loop is a rather slow way of operating on Numpy arrays. The idea of Numpy is to do vectorised high-level calls, so the actual looping can happen in optimised C code. Commented Sep 11, 2015 at 15:27

1 Answer 1

4

To take advantage of broadcasting, you have to insert new axes for fact at the right places:

a *= fact[:, np.newaxis, :, np.newaxis, np.newaxis] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.