Medha Shringari
Medha Shringari

Reputation: 11

Trying to multiply a matrix with its transpose but not getting any result

This code is for multiplication of a matrix with its transpose:

import numpy as np

def multiply_At_A(A):
    dim1 = A.shape[0]
    dim2 = A.shape[1]
    matrix = np.zeros([dim2,dim2])
    
    for i in range(dim2):
        for j in range(dim2):
            for k in range(dim1):
                matrix[i,j]==A[i,k]*A[k,j]
        return matrix
    A=np.array([[1,2,3],[4,5,6],[7,8,9]])
    print(matrix)

I was supposed to get a result but i am not getting any result

Upvotes: 1

Views: 195

Answers (1)

Majid
Majid

Reputation: 638

This is the recommended solution:

A.dot(A.transpose())

Also, below is the fixed version of your code:

import numpy as np


def multiply_At_A(A):
    dim1, dim2 = A.shape
    matrix = np.zeros([dim2, dim2])

    for i in range(dim1):
        for j in range(dim2):
            for k in range(dim2):
                matrix[i, j] += A[i, k] * A[j, k]
    return matrix


A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(multiply_At_A(A))

Upvotes: 3

Related Questions