我想将两个2D数组相乘,使第一个数组的行与第二个数组的列相乘。
所以我调换了第二个数组,使其列更改为transposedone的行。然后我逐个从2D数组中提取出两行,并将它们视为两个简单列表,将它们相乘并将它们存储在另一个列表中。
我想将它们存储为生成的2D数组的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)
答案 0 :(得分:1)
以下是否适合您:
[sum(a * b for a, b in zip(*combined_row)) for combined_row in zip(mat_A, zip(*mat_B))]
这转换mat_B
,每行压缩两个矩阵,然后将每列的行相乘并将相乘的值相加,使一个值列表。
答案 1 :(得分: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]]
答案 2 :(得分: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的转置