How do I multiply two matrices in python?

Asked

Viewed 10,417 times

-2

def multM(a, b): '''essa foi a função que eu tentei fazer'''
    if len(a) == len(b[0]):
        r = []
        for i in range(len(a)):
            r.append([])
            for j in range(len(b[0])):
                for k in range(len(a)):
                    val = a[i][j] * b[k][i]
                r[-1].append(val)
    return r
  • Have you considered using the np.matmul(a,b) ?

  • Already, but this is for an activity and I have to create a function for it anyway, thank you!

  • Good. I hope you want to do this only to train. Because it doesn’t make much sense. The most appropriate is to use a library like numpy.

2 answers

2

You can do two functions:

  • getLinha(matriz, n) returns a list of line values n.

  • getColuna(matriz, n) returns a list of column values n.

Implementing, we have:

def getLinha(matriz, n):
    return [i for i in matriz[n]]  # ou simplesmente return matriz[n]

def getColuna(matriz, n):
    return [i[n] for i in matriz]

mat1 = [[2, 3], [4, 6]]            # uma matriz 2x2
mat1lin = len(mat1)                # retorna 2
mat1col = len(mat1[0])             # retorna 2

mat2 = [[1, 3, 0], [2, 1, 1]]      # uma matriz 2x3
mat2lin = len(mat2)                # retorna 2
mat2col = len(mat1[0])             # retorna 3

matRes = []                        # deverá ser uma matriz 2x3
for i in range(mat1lin):           
    matRes.append([])

    for j in range(mat2col):
        # multiplica cada linha de mat1 por cada coluna de mat2;
        listMult = [x*y for x, y in zip(getLinha(mat1, i), getColuna(mat2, j))]

        # e em seguida adiciona a matRes a soma das multiplicações
        matRes[i].append(sum(listMult))

print(matRes)

Run the generated code as output [[8, 9, 3], [16, 18, 6]].

Using classes would be more practical:

class Matriz:
    def __init__(self, mat):
        self.mat = mat
        self.lin = len(mat)
        self.col = len(mat[0])

    def getLinha(self, n):
        return [i for i in self.mat[n]]

    def getColuna(self, n):
        return [i[n] for i in self.mat]

    # opcional: dar overload no operador de multiplicação
    def __mul__(self, mat2):
        matRes = []

        for i in range(self.lin):           
            matRes.append([])

            for j in range(mat2.col):
                listMult = [x*y for x, y in zip(self.getLinha(i), mat2.getColuna(j))]
                matRes[i].append(sum(listMult))

        return matRes

Run this code using

mat1 = Matriz([[2, 3], [4, 6]])
mat2 = Matriz([[1, 3, 0], [2, 1, 1]])
print(mat1*mat2)

takes off [[8, 9, 3], [16, 18, 6]].

0

You can use the function zip and the list comprehension.
The zip function takes lists and builds a list of tuples with the list members. And list comprehension is a quicker way to write loops is simple.

This is basically the code:

numerosX = [3, 5, 7, 11]
numerosY = [4, 6, 8, 12]

numerosZ = [x*y for x, y in zip(numerosX, numerosY)]
print(numerosZ) # Imprime [12, 30, 56, 132]
  • 2

    Just remembering that matrix multiplication is not enough to multiply element by element. Matrix multiplication will always consider multiplication between a row and a column, causing a 1:4 matrix multiplied by a 4:1 to result in a 1:1, not a 1:4.

Browser other questions tagged

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