AliALiyev
AliALiyev

Reputation: 26

How to multiply two matrices?

I have tried to write a function for multiplying two matrices. Matrices are represented by lists inside lists like that [[1, 2], [3, 4]]. Although it gives result, it is not correct.

def Matrice_multiplicator(a, z):
    if len(a[0])==len(z):
        m=Matrice_create(len(a))
        b=0
        c=0
        k=1-1
        while b<len(a):
            for i in range(len(a[b])):
                while c<len(a[0]):
                    k+=a[b][c]*z[c][b]
                    print(k)
                    c+=1
                m[b].append(k)
            b+=1
        return m
    else:
        return "Not multiplicable"

Upvotes: 0

Views: 90

Answers (1)

JohanC
JohanC

Reputation: 80439

A matrix multiplication in standard Python could look like:

def matrix_multiplication(A, B):
    a = len(A)
    b = len(A[0])
    c = len(B[0])
    if b != len(B):
        print (f"Wrong combination of dimensions: {a}x{b} and {len(B)}x{c}")
    else:
        return [[sum([A[i][k]*B[k][j] for k in range(b)]) 
                 for j in range(c)]
                for i in range(a)]

A = [[1, 2, 3],
     [4, 5, 6]]
B = [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12]]

print(matrix_multiplication(A, B))

Result:

[[38, 44, 50, 56],
 [83, 98, 113, 128]]

Upvotes: 2

Related Questions