I am trying to create a code that does matrix multiplication without numpy or zip*. The code works fine when I define the zero matrix that receives the result of the multiplication, but the results overlap when I try to make the variable get defined by a loop.
I obviously can't just define the empty matrix because the compiler gives an index out of range error, and the multiplication resultant matrix changes depending on input. I provided a screenshot to the empty matrix when it is defined and when letting the code create the empty matrix.
def empty(X, Y):
P=[]
row=[]
for r in range(len(Y[0])):
row.append(0)
for t in range(len(X)):
P.append(row)
return P
def multiply(X, Y):
P=empty(X, Y)
#P=[[0, 0], [0, 0], [0, 0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
P[i][j] += X[i][k] * Y[k][j]
return P
def One(X, Y):
x=[]
b=[]
count=0
for i in range(len(X)):
b.append(1)
x.append(b)
x.append(X)
return x
d=[[1, 2], [2, 3], [2, 4]]
b=[[2, 4], [5, 6]]
print(multiply(d,b))
print(empty(d,b))
The two matrices look the same in the output window. The first one is the one I manually defined as P=[[0,0],[0,0],[0,0]]
.
The second one is the one created from the empty()
function. The result is different from the multiplication function; it is overwritten for some reason.
P
reference the same list objectrow
. So when you changeP[i][j]
you are effectively changingP[:][j]
. You can make a copy ofrow
like this:P.append(row[:])
X
and other calledx
in this case since this can lead to misunderstandings.