Skip to main content
 首页 » 编程设计

python之python中文件之间的矩阵乘法

2024年10月01日7kuangbin

import linecache 
 
fileA = open('matrixA.txt', 'r' ) 
 
line2 = linecache.getline('matrixA.txt', 2) 
line3 = linecache.getline('matrixA.txt', 3) 
line4 = linecache.getline('matrixA.txt', 4) 
 
two = line2.split() 
list2 = list(map(int, two)) 
 
three = line3.split() 
list3 = list(map(int,three)) 
 
four = line4.split() 
list4 = list(map(int, four)) 
 
listA = [list2]+[list3]+[list4] 
print (listA) 
 
fileB = open('matrixB.txt', 'r') 
 
Bline2 = linecache.getline('matrixB.txt', 2) 
Bline3 = linecache.getline('matrixB.txt', 3) 
Bline4 = linecache.getline('matrixB.txt', 4) 
 
btwo = Bline2.split() 
blist2 = list(map(int, btwo)) 
 
bthree = Bline3.split() 
blist3 = list(map(int,bthree)) 
 
bfour = Bline4.split() 
blist4 = list(map(int, bfour)) 
 
listB = [blist2] + [blist3] + [blist4] 
print (listB) 
 
q = listA[0] # 
h = listB[0] #This part dosn't work  
aq = q*h     # 
print(aq)    # 
 
//for i in range(listA): 

到目前为止,我的 2 个文件 A 中的代码打印为:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

文件 B 打印为:

[[3, 3, 9], [7, 4, 8], [4, 20, 30]]

我如何让这两个矩阵相乘,我知道你需要位置,但我不知道如何进行循环。

请您参考如下方法:

我假设你已经正确加载了你的 *.txt 数据(你开始从第二行读取你的数据),然后将它相乘最简单的方法是将它转换为 numpy 数组并使用 np.dot.

import numpy as np 
A = np.asarray(listA) 
B = np.asarray(listB) 
res = np.dot(B,A) 
print(res) 

或者你可以在没有 numpy 的情况下通过索引列表来做到这一点:

res = [[0] * len(listA[0]) for _ in range(len(listB))] 
for i in range(len(listB)): 
    for j in range(len(listA[0])): 
        for k in range(len(listA)): 
            res[i][j] += listB[i][k]*listA[k][j] 
print(res) 

为确保您的矩阵可以相乘,请先检查维度:

if len(listA)==len(listB[0]): 
    res = [[0] * len(listA[0]) for _ in range(len(listB))] 
    for i in range(len(listB)): 
        for j in range(len(listA[0])): 
            for k in range(len(listA)): 
                res[i][j] += listB[i][k]*listA[k][j] 
    print(res) 
else: 
    print("ERROR! Size Mismatch")