XCalibur
XCalibur

Reputation: 11

How to perform Matrix Multiplication in Python

I have been trying to complete all matrix functions in python but i am stuck while multiplying 2 matrices. However , I can only get the last column to be added with one way and the diagonal elements in other. Could you please help me . Here is the image i used as reference https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fgeekboots.sfo2.cdn.digitaloceanspaces.com%2Fpost%2Fmatrix-multiplication-in-python-1583987059605.jpg&f=1&nofb=1 my code :-

R = int(input("Enter number of rows: "))
C = int(input("Enter number of columns: "))
mat1 = [[3,4],[2,1]]
mat2 = [[1,5],[3,7]]
mat3=[]
for i in range(R):
    for j in range(C):
        a = 0
        for k in range(C):
            a+=mat1[i][k]*mat2[k][j]
    mat3.append(a) 

print(mat3)

In this way i can only get the last elements of column 2

Other way :-

R = int(input("Enter number of rows: "))
C = int(input("Enter number of columns: "))
mat1 = []
mat2=[]
for i in range(R):
    a = []
    for j in range(C):
        a.append(float(input("Enter the value for matrix 1: ")))
     mat1.append(a)

print('----------------------------')
for i in range(R):
     a = []
     for j in range(C):
         a.append(float(input("Enter the value for matrix 2: ")))
     mat2.append(a)

print('----------------------------')



mat3=[]

for i in range(R):
    a = 0
    for j in range(C):
        a+=(mat1[i][j]*mat2[i][j])
    mat3.append(a)
print(mat3)

in this way i can get only the left diagonal elements

Upvotes: 1

Views: 2099

Answers (2)

nTerior
nTerior

Reputation: 169

You can use numpy!

  1. Add your import statement, e.g.
import numpy as np
  1. Convert your matrices (which are just arrays) to numpy's ndarrays
mat1 = np.array(mat1)
mat2 = np.array(mat2)
  1. Multiplication
result = np.matmul(mat1, mat2)

Reference: NumPy Docs

Upvotes: 1

Selvaganapathy
Selvaganapathy

Reputation: 166

Hello the variable k you are using will save the results in position 0 and 1 in first loop and it stores the second column results also in same position 0 and 1. So you won't get the final result of first columns except the last one. Instead you can initialize an empty array with values 0 and you can add the values in their respective positions.

mat1 = [[3,4],[2,1]

mat2 = [[1,5],[3,7]]   

result = [[0, 0],[0, 0]]

for i in range(len(mat1)):

    for j in range(len(mat2[0])):

        for k in range(len(mat2)):

            result[i][j] += mat1[i][k] * mat2[k][j]

for r in result:
    print(r)

Upvotes: 2

Related Questions