Addition, multiplication and transpose of lists in python.

Addition of matrices:-

Take the size of the matrix as user input, accept the two matrices and print the resultant matrix after adding the original two matrices.

row=int(input("enter the row"))
column=int(input("enter the column"))
a=[]
b=[]
print("1st matrix elements")
for i in range(0,row):
 a1=[]
 for j in range(0,column):
  e=int(input())
  a1.append(e)
 a.append(a1)
print("2nd matrix elements")
for i in range(0,row):
 b1=[]
 for j in range(0,column):
  e1=int(input())
  b1.append(e1)
 b.append(b1)
c=[]
for i in range(0,row):
 c1=[]
 for j in range(0,column):
  c1.append(0)
 c.append(c1)
for i in range(0,row):
 for j in range(0,column):
  c[i][j]=a[i][j]+b[i][j]
print(c)

Output:-

We have taken inputs the row and column number , accepted the values of two lists. Then we made a zeros matrix c[] of the accepted order, and within loop , we changed the value of c[i][j] to the addition of a[i][j] and b[i][j] .

Multiplication of matrices:-

row=int(input("enter the row matrix1"))
column=int(input("enter the column matrix1"))
row1=int(input("enter the row matrix2"))
column1=int(input("enter the column matrix2"))
a=[]
b=[]
print("1st matrix elements")
for i in range(0,row):
 a1=[]
 for j in range(0,column):
  e=int(input())
  a1.append(e)
 a.append(a1)
print("2nd matrix elements")
for i in range(0,row1):
 b1=[]
 for j in range(0,column1):
  e1=int(input())
  b1.append(e1)
 b.append(b1)
c=[]
for i in range(0,row):
 c1=[]
 for j in range(0,column1):
  c1.append(0)
 c.append(c1)
for i in range(0,row):
 for j in range(0,column1):
  for k in range(0,column):
   c[i][j]+=a[i][k]*b[k][j]
print(c)

Output:-

Rule of matrix multiplication says that, two matrices Aik and Bmj are only multiplicable if k=m and the resultant matrix will of the order Cij.

So row and column of resultant matrix is row of first matrix and column of second matrix. And also notation for multiplication is summation of Aik*Bkj ,where k is the column of the first matrix or row of the second matrix.

Transpose of a matrix:-

Example of a transpose of a matrix is

A=[[1,2,3],[4,5,6],[7,8,9]]

transpose of A=AT

AT=[[1,4,7],[2,5,8],[3,6,9]] , so we can see rows are converted to columns and vice versa. So the notation is ATij=Aji

row=int(input("enter row"))
column=int(input("enter column"))
a=[]
print("matrix elements")
for i in range(0,row):
 a1=[]
 for j in range(0,column):
  e=int(input())
  a1.append(e)
 a.append(a1)
print("original matrix",a)
c=[]
for i in range(0,row):
 c1=[]
 for j in range(0,column):
  c1.append(0)
 c.append(c1)
for i in range(0,row):
 for j in range(0,column):
  c[i][j]=a[j][i]
print("transposed matrix",c)
Output

Leave a comment

Design a site like this with WordPress.com
Get started