1

Say I have:

a = np.array([[2, 4],
              [6, 8]])    
b = np.array([[1, 3],
              [1, 5]])

I want to get to:

c = np.array([[20,32],
              [28, 44]])

where c is the result of multiplying each column of a by b, then summing that result along the first axis.

I.e.:

print(np.sum(a[:, 0] * b, axis=1))
[20 32]

print(np.sum(a[:, 1] * b, axis=1))
[28 44]

Can I do through broadcasting rather than:

  • using np.apply_along_axis or
  • looping through each column?
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235

1 Answers1

4

You can use np.dot -

b.dot(a).T

Alternatively, using np.einsum (for the kicks maybe) -

np.einsum('ij,ki->jk',a,b)
Divakar
  • 218,885
  • 19
  • 262
  • 358