Matrix Calculation Numpy

96 Views Asked by At

I am trying to calculate Rij = Aij x Bji/Cij with numPy broadcasting. Also raise an exception if matrices are not the same size (n × n).

I am not so sure if this is correct or if I should be doing element wise or matrix wise. could anyone tell me how to do it

A = [[(i+j)/2000 for i in range(500)] for j in range(500)]
B = [[(i-j)/2000 for i in range(500)] for j in range(500)]
C = [[((i+1)/(j+1))/2000 for i in range(500)] for j in range(500)]



def matrix_R(A,B,C):

    A1 = np.array(A)
    B1 = np.array(B)
    C1 = np.array(C)   
    eq = (A1 @ np.transpose(B1)) 
    Rij = np.divide(eq, C1)
    
    if len(A1) != len(B1) or len(A1) != len(C1):
        raise ArithmeticError('Matrices are NOT the same size.')
    return Rij
    


matrix_R(A, B, C)
1

There are 1 best solutions below

0
Asthom On

The @ is the matrix product operator for numpy arrays.

np.array([[1, 2], [3, 4]]) @ np.array([[5, 6], [7, 8]])

is

np.array([[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]])

For element multiplication you may use * which does element-wise product for numpy arrays.

np.array([[1, 2], [3, 4]]) * np.array([[5, 6], [7, 8]])

is

np.array([[1*5, 2*6], [3*7, 4*8])

To answer your question, you can compute R the matrix of Rij = Aij x Bji/Cij with:

R = np.divide(np.multiply(A, np.transpose(B)), C)

or equivalently and shorter:

R = A * B.T / C