Problem with multiplication of matrices in python

Asked

Viewed 329 times

-1

Can anyone tell me what the problem is with this code ? (I’m a beginner).

import random
def mult():
    num_l1, num_c1 = len(mat1), len(mat1[0])
    num_l2, num_c2 = len(mat2), len(mat2[0])
    for i in range(num_l1):
        resp.append([])
        for j in range(num_c2):
            resp[i].append(0)
            for m in range(num_c1):
                resp[i][j] += mat1[i][m] * mat2[m][j]
    return resp
mat1 = []
mat2 = []
resp = []
for i in range(3):
    mat1.append([0] * 3)
for i in range(3):
    mat2.append([0] * 3)
for i in range(len(mat1)):
    for j in range(len(mat1)):
        mat1[i][j] = random.randint(0, 9)
for i in range(len(mat1)):
    for j in range(len(mat1)):
        mat2[i][j] = random.randint(0, 9)

mult()

  • What’s the mistake? ...

  • The code simply does not execute, or it appears that nothing happens

1 answer

1

Your code doesn’t print anything so you’re thinking it does nothing, I made some modifications to your code:

  • Your method does not receive any parameter pass the matrices by parameter def mult(mat1, mat2);
  • Call the method inside a print so you can see the results print(mult(mat1, mat2))

_

import random
def mult(mat1, mat2):
    num_l1, num_c1 = len(mat1[0]), len(mat1[1])
    num_l2, num_c2 = len(mat2[0]), len(mat2[1])
    for i in range(num_l1):
        resp.append([])
        for j in range(num_c2):
            resp[i].append(0)
            for m in range(num_c1):
                resp[i][j] += mat1[i][m] * mat2[m][j]
    return resp
mat1 = []
mat2 = []
resp = []
for i in range(3):
    mat1.append([0] * 3)
for i in range(3):
    mat2.append([0] * 3)
for i in range(len(mat1)):
    for j in range(len(mat1)):
        mat1[i][j] = random.randint(0, 9)
for i in range(len(mat1)):
    for j in range(len(mat1)):
        mat2[i][j] = random.randint(0, 9)

print(mult(mat1, mat2))

Browser other questions tagged

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