Search code examples
pythonnumpymatrixmedian

Fastest way for axis-wise matrix multiplication in python?


I want to multiply the same matrix axis-wise, where a matrix A has the shape (n, d): e.g. (3, 5):

A = array([[ 0,  3,  6,  9, 12],
           [ 1,  4,  7, 10, 13],
           [ 2,  5,  8, 11, 14]])

I don't know whether this multiplication or product has a name, because I didn't find anything common. But my goal is, to multiply this matrix, such that all rows are multiplied with all the other rows, and creates a new matrix (mul) with the shape (n, n):

formula

In the end I would like to calculate the median along the third axis np.median(mul, axis=2).

formula

I implemented this calculation the way below, with a double for-loop, but unfortunately this has a time-complexity of O(n²). Therefore, it takes a really long time to calculate it for bigger matrices.

temp_list = []
for i in range(0, matrix.shape[0]):
    row = []
    for j in range(0, matrix.shape[0]):
        mul = matrix[i, :] * matrix[j, :]
        row.append(np.median(mul))
    temp_list.append(row)
return np.asarray(temp_list)

Is there a way to make this calculation more time efficient?


Solution

  • import numpy as np
    
    A = np.array([[ 0,  3,  6,  9, 12],
                  [ 1,  4,  7, 10, 13],
                  [ 2,  5,  8, 11, 14]])
    
    mul = A[None, :, :] * A[:, None, :]
    
    np.median(mul, axis=2)
    
    # array([[36., 42., 48.],
    #        [42., 49., 56.],
    #        [48., 56., 64.]])