python 求两个矩阵相乘

2021-01-28 10:05:10 浏览数 (1)

参考链接: Python程序可将两个矩阵相乘

方法一: 

def matrix_multiply(matrix1,matrix2):

    new_matrix = [[0 for i in range(len(matrix1))] for j in range(len(matrix1))]

    for i in range(len(matrix1)):

        for j in range(len(matrix1)):

            for x in range(len(matrix1)):

                new_matrix[i][j] = matrix1[i][x]*matrix2[x][j]   

    return new_matrix

matrix1 = [[1,2,3], [4,5,6], [7,8,9]]

matrix2 = [[2,2,2], [3,3,3], [4,4,4]]

new_matrix = matrix_multiply(matrix1, matrix2)

print(new_matrix)  # [[20, 20, 20], [47, 47, 47], [74, 74, 74]]

方法二: 

import numpy as np

matrix1 = [[1,2,3], [4,5,6], [7,8,9]]

matrix2 = [[2,2,2], [3,3,3], [4,4,4]]

print(np.dot(matrix1,matrix2))

"""

[[20 20 20]

 [47 47 47]

 [74 74 74]]

"""

0 人点赞