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]]
.
Have you considered using the
np.matmul(a,b)
?– FourZeroFive
Already, but this is for an activity and I have to create a function for it anyway, thank you!
– Pedro Fernandes
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.
– Gabriel Machado