0

I have two 2-D matrices which have a shared axis. I want to get a 3-D array that holds the results of every pairwise multiplication made between all the combinations of vectors from each matrix along that shared axis. What is the best way to achieve this? (assuming that the matrices are big)

As an illustration, let's say I have 100 technicians and 1000 customers. For each of these individuals I have a 1-D array with ones and zeros representing their availability on a each day of the week. That's a 7x100 matrix for the technicians, a 7x1000 matrix for the customers.

import numpy as np

technicians = np.random.randint(low=0,high=2,size=(7,100))
customers = np.random.randint(low=0,high=2,size=(7,1000))
result = solution(technicians, customers)
result.shape  # (7,100,1000)

I want to find for each technician-customer couple the days they are both available. If I perform a pairwise multiplication between each combination of technician availability and customer availability I get a 1-D arrays that shows for each couple whether they are both available on these days. Together they create the 3-D array I'm aiming for, shaped something like 7x100x1000.

Thanks!

PandaZ
  • 127
  • 3
  • 12

1 Answers1

1

Try

ans = technicians.reshape((7, 1, 100)) * customers.reshape((7, 1000, 1))

We make use of numpy.broadcasting.

General Broadcasting Rules: When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

(1) they are equal, or (2) one of them is 1

Now, we are matching the shape of technicians and customers as

technician       : 7 x 1    x 100
customers        : 7 x 1000 x 1
Result (3d array): 7 x 1000 x 100

using reshape. Then, we can apply elementwise multiplication with *.

Tai
  • 7,684
  • 3
  • 29
  • 49