1

我想以这样的方式将两个二维数组相乘,即第一个数组的行将与第二个数组的列相乘。

所以我转置了第二个数组,使其列更改为转置的行。然后我从二维数组中一一提取两行并将它们视为两个简单列表,将它们相乘并将它们存储在另一个列表中。

我想将它们存储为结果二维数组的 00 (行列)元素。我该怎么做?

NO_OF_ROWS_A=int(input("Enter the no. of rows in A: "))
NO_OF_COLUMNS_A=int(input("Enter the no. of columns in A: "))
NO_OF_ROWS_B=int(input("Enter the no. of rows in B : "))
NO_OF_COLUMNS_B=int(input("Enter the no. of columns in B: "))

mat_A=[[] for i in range(NO_OF_ROWS_A)]
for i in range(NO_OF_ROWS_A):
    for j in range (NO_OF_COLUMNS_A):
        print("Enter",i,j,"element for mat A: ")
        a=int(input())
        mat_A[i].append(a)

mat_B=[[] for i in range(NO_OF_ROWS_B)]
for i in range(NO_OF_ROWS_B):
    for j in range (NO_OF_COLUMNS_B):
        print("Enter",i,j,"element for mat B: ")
        b=int(input())
        mat_B[i].append(b)

import itertools
mat_B_trans = list(itertools.zip_longest(*mat_B))#transposes B to change its col into row

sum_list_x=0

mat_C=[[] for i in range(NO_OF_ROWS_A)]
for i in range(NO_OF_ROWS_A):
    for j in range(NO_OF_COLUMNS_B):
        for i in range(NO_OF_ROWS_A):#extracts row of A
            list_row_a=mat_A[i]
        for j in range(NO_OF_COLUMNS_B):#extracts row of trans_B which is col of B
            list_column_b=mat_B_trans[i]
        list_temp_multiple=[a*b for a,b in zip(list_row_a, list_column_b)]#list of multiples of same indices of A & B
        sum_list=sum(list_temp_multiple)#sum of prev list elemets
        sum_list_x=sum_list_x + sum_list

        c = sum_list_x
        mat_C[i].append(c)
print(mat_C)
4

3 回答 3

1

以下内容是否适合您:

[sum(a * b for a, b in zip(*combined_row)) for combined_row in zip(mat_A, zip(*mat_B))]

这将转置mat_B,压缩每行的两个矩阵,然后将每列的行相乘并将相乘的值相加,形成一个值列表。

于 2013-05-05T16:03:18.793 回答
0

使用NumPy,你的整个程序可以写成:

import numpy as np

mat_A = np.matrix(input('Enter matrix A: '))
mat_B = np.matrix(input('Enter matrix B: '))
mat_C = mat_A * mat_B
print(mat_C)

产量

Enter matrix A: [[1,2], [3,4]]
Enter matrix B: [[5,6], [7,8]]
[[19 22]
 [43 50]]
于 2013-05-05T16:22:45.207 回答
0
[[sum(a*b for a,b in zip(mat_A_row,mat_B_col)) for mat_A_col in zip(*mat_B)] for mat_A_row in mat_A]

zip(*X) 以元组格式返回矩阵 X 的转置

于 2016-12-04T07:12:39.790 回答