Home > Software design >  How to calculate pairwise inside a matrix
How to calculate pairwise inside a matrix

Time:12-22

how to perform pair operations on more than 2 lists

Example

If my matrix have 2 lists (L,M) I calculate the dot product and the results are [[M.M M.L , L.M LL]]

How to calculate the same operation for matrices that have more than 2 lists in a way that the result is a symmetric matrice

x = np.array([[1, 3, 5],[1, 4, 5],[2,6,10]])

How to perform pairwise analysis ?

CodePudding user response:

Solution 1: An alternative to the brute force below is using np.einsum, but it is not simple to use that function. This link has an explanation on how to use it, https://ajcr.net/Basic-guide-to-einsum/. See Solution 2 on how matrix is defined.

np.einsum('ij,jk', matrix,matrix.T)
Out[35]: 
array([[35, 38],
       [38, 42]])
matrix = np.array([L, M, N])  # matrix with 3 lists
np.einsum('ij,jk', matrix,matrix.T)
Out[37]: 
array([[ 35,  38,  70],
       [ 38,  42,  76],
       [ 70,  76, 140]])

Solution 2 for smaller matrices. Explanation below:

def dot_pairwise(matrix):
    return [[np.dot(i, j) for j in matrix]  for i in matrix]

dot_pairwise(matrix)

Explanation:

import numpy as np
L = np.array([1, 3, 5])
M = np.array([1, 4, 5])
N = np.array([2, 6, 10])

matrix = np.array([L, M, N]) # matrix with 3 lists
# matrix = np.array([L, M])  # matrix with 2 lists to replicate your example


# Initialize an empty result list
result = []

for i in matrix:
    row = []  # Initialize an empty row
    for j in matrix:
        # Calculate the dot product between the ith and jth lists using numpy.dot
        print(i,j) # to print the matrices
        dot_product = np.dot(i, j)
        row.append(dot_product)  # Add the dot product to the row
    result.append(row)  # Add the row to the result

print(result)  # [[LL, LM, LN], [ML, MM, MN], [NL, NM, NN]]

This is the result using L, M matrix:

[1 3 5] [1 3 5] LL
[1 3 5] [1 4 5] LM
[1 4 5] [1 3 5] ML
[1 4 5] [1 4 5] MM
[[35, 38], [38, 42]] # dot products

CodePudding user response:

Alternative from this answer, slightly changed:

np.tensordot(x, x, axes=(1,1))
  • Related