Joe Joe - 3 years ago 162
Python Question

matrix multiplying between files in python

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):


So I have this code so far from my 2 files file A prints as:


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


And file B prints as:


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


How would I get these two matrices to multiply, I know you would need positions but I don't know how to do the loop.

Answer Source

I assume you have loaded your *.txt data correctly (you start to read your data from the second line), then to multiply it the simple one is by converting it to numpy array and use np.dot.

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

or you can do that without numpy by indexing the list:

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)

to make sure your matrix can be multiplied, check the dimension first:

if len(listA)==len(listB[0]):
    A = np.asarray(listA)
    B = np.asarray(listB)
    print(np.dot(B,A))
else:
    print("ERROR! Size Mismatch")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download