Multiplication of matrices in Python

Asked

Viewed 5,357 times

0

Hello, I’m making a python algorithm that makes the product between two matrices, but I’m having trouble displaying the resulting matrix

matriz = []
linha = []
linha2= []
matriz_result = []
result = 0
lista = []
nlin,ncol= map(int,input().split())
for i in range(0,nlin):
 valor = (input().split())
 valor = list(map(int,valor))
 linha.append(valor)
 matriz.append(linha)


matriz2 = []
nlin2,ncol2 = map(int,input().split())
for i in range(0,nlin2):
 valor = (input().split())
 valor = list(map(int,valor))
 linha2.append(valor)
 matriz2.append(linha2)

for i in range(nlin):
 if ncol!=nlin2:
     print("ERRO")
 for j in range(ncol):
      for h in range(0,1):
           for k in range(ncol):
                result += matriz[i][i][k]*matriz2[k][k][i]
                matriz_result.append(result)



print(matriz_result)

I have to place the matrix inputs on the same line, there for some reason an element of the matrix is given by three parameters.

Someone tell me what I need to change in the code?

  • You had not put the [python] tag on your question. Without it, almost no one would find it.

  • @Lucas, matrices have 3 dimensions? (expected 2); if you print the value of matriz is looking something like [[[0, 1], [1, 0]], [[0, 1], [1, 0]]]

1 answer

0

Mano , when you asked the user to enter the list you put the line in the value variable , then turns it into a list and then puts it inside another list , so it is an array with 3 indexes .

Puts straight into line variable .

for i in range(0,nlin):
 linha = (input().split())
 linha = list(map(int,linha))
 matriz.append(linha)

But the Resulting Matrix is not only with the elements, it shows all the factors of each element .

And also not calculating the factors right , the next factor is always being the sum of the previous factors .

Besides that the for j in range(ncol): must be with ncol2 getting for j in range(ncol2): for in the for i in range(nlin): is defined the amount of rows of the resulting matrix that will be the same amount of rows of the matrix 1 and in the for j in range(ncol): will be defined the amount of columns of the resulting matrix that will be the same amount of columns of matrix 2 and not 1 as is represented .

The for k in range(ncol): could also be written with nlin2 but not with nlin nor with ncol2 because in this case is defined the amount of factors that sum will result in each element of the resulting matrix and this amount of factors is the same as the value of the columns of the matrix 1 and the rows of the matrix 2 .

That one for h in range(0,1): also unnecessary , as the way it is would run only once but all code will run at least once .

On that website Page in Scriptbrasil shows a correct way to multiply matrices .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.