Finding whether each element in matrix is reciprocal of it's transpose in 3d tensor

58 views Asked by At

I have a numpy matrix of shape m * n * n, meaning I have m n*n square matrices. For each matrix, I must have elements present in such a way so that the transpose indexes are reciprocal of each other. If any occurrence or violation is detected, return False, otherwise, return True.

In the image the answer is true because we have four matrices of shape 3*3, and every element in the matrix is reciprocal of the transpose element.

This code is to be deployed, so I would expect that the process takes the least amount of time and maximum parallelism is achieved.

The image

I don't know how to approach it. I tried ChatGPT, but it gave me possible worst results

1

There are 1 answers

6
Oskar Hofmann On

First of all, please note that in your example your condition might not be fulfilled as you want to check if entries on transpose indices are exactly reciprocal to each other. But 0.11111111 * 9 != 1. I assume the value 0.11111111 is 1/9 but 1/9 cannot be exactly stored as a floating point number in base 2.

Anyway, to check if one n x n array fulfills your requirement, you can multiply the array element-wise with its tranpose matrix and check if all elements in this matrix are 1:

import numpy as np

a = np.array([[1,0.25,4],[4,1,9], [0.25, 1/9, 1]])

b = np.multiply(a, a.T)

# check if any values in b are not 1
print(np.any(b != 1.0) 

If you run into issues with the exact equality (as mentioned above) you might want to use np.isclose() instead.

For your m x n x n array you can simply loop over all m arrays. There might be a more efficent way but afaik, there is no direct way to apply functions to 2D-slices of a 3D-array:

def check_reciprocal(mats: np.ndarray) -> bool:
   for mat in mats:
      if np.any(np.multiply(mat, mat.T) != 1.0):
         return False
   return True

To speed it up, one could potentially reshape the 2D-matrices into 1D-arrays and then use np.apply_along_axis() or compile the function using numba.