I'm trying to multiply matrices with python. The objective of the program is to have three matrices as parameters: A, B and res (result matrix) that will be completed with the result of multiplying the matrices represented by the lists of lists. The program must accept both lists of lists and matrices of NumPy.
I wrote the following code:
'''
multMatrices(a, b, res): Completa los elementos de res
con el resultado de multiplicar las matrices representadas por
las listas de listas a y b.
'''
def multMatrices(A, B, res):
filas_A = len(A)
cols_A = len(A[0])
filas_B = len(B)
cols_B = len(B[0])
res = matrizCeros()
if cols_A != filas_B:
print("No es posible multiplicar las matrices. Dimensiones incorrectas.")
return
# Se crean las dimensiones de la matriz
# Lss dimensiones deben ser filas_A x cols_B
res = [[0 for row in range(cols_B)] for col in range(filas_A)]
#print(res) #Cuidado con este print
#preguntar por las matrices de numpy con instance
if isinstance(A,np.matrix) and isinstance(B,np.matrix):
#res = np.matmul(A, B)
np.copyto(res,np.matmul(A, B))
else:
#Si isinstance devuelve False, se ejecuta esta sección original
for i in range(filas_A):
for j in range(cols_B):
for k in range(cols_A):
res[i][j] += A[i][k] * B[k][j]
When I try list lists the program works, but not with NumPy arrays:
C = [[1,1,1],[1,1,1],[1,1,1]]
D = [[1,1,1],[1,1,1],[1,1,1]]
E = matrizCeros()
X = np.matrix([[1, 2], [3, 4]])
Y = np.matrix([[1, 2], [3, 4]])
Z = matrizCeros()
print("Resultado Mult:",multMatrices(C, D, E))
print("Resultado Mult:",multMatrices(X, Y, Z))
#Resultados:
Resultado Mult: [[3, 3, 3], [3, 3, 3], [3, 3, 3]]
No es posible multiplicar las matrices. Dimensiones incorrectas.
Resultado Mult: None
I have not been able to identify what I am doing wrong. I appreciate the feedback provided.