matrix addition in python input from user

Solutions on MaxInterview for matrix addition in python input from user by the best coders in the world

showing results for - "matrix addition in python input from user"
Arianna
16 Feb 2019
1#getting dimension of matrix
2
3print "enter n for nxn matrix"
4n = input()
5
6matrix1 = []
7matrix2 = []
8
9#taking elements of first matrix
10
11print "Enter elements of first matrix"
12for i in range(0,n):
13
14  #taking elements of first column
15
16  print "Enter elements of ",i,"column, seperated by space"
17
18  #raw_input().split() will split the string
19  #'1 2 34'.split() will give ['1', '2', '34']
20  #map will convert its elements into integers [1, 2, 34]
21
22  matrix1.append(map(int,raw_input().split()))
23
24print "Matrix 1 is",matrix1
25
26#taking elements of second matrix
27
28print "Enter elements of second matrix"
29for i in range(0,n):
30  #Similar to input taken for 1 matrix
31
32  print "Enter elements of ",i,"column, seperated by space"
33  matrix2.append(map(int,raw_input().split()))
34
35print "Matrix 2 is",matrix2
36
37#adding
38
39add_matrix = []
40for i in range(0,n):
41  a = []
42  for j in range(0,n):
43
44
45    #making a addition matrix's column to append
46    #making a 1D matrix with elements as sum of elements of
47    #respective columns of both matrices
48
49    a.append(matrix1[i][j]+matrix2[i][j])
50  add_matrix.append(a)
51print "Addition of matrix is",add_matrix
52
53#multiplication
54multi_matrix = []
55for i in range(0,n):
56  a = []
57  for j in range(0,n):
58    summ = 0
59    for k in range(0,n):
60      summ = summ+(matrix1[i][k]*matrix2[k][j])
61    a.append(summ)
62  multi_matrix.append(a)
63print "matrix1 x matrix 2 =",multi_matrix
64
65#transpose of matrix1
66
67tr_matrix=[]
68
69for i in range(0,n):
70  a = []
71  for j in range(0,n):
72
73    #matrix1[j][i] will give row of matrix 1
74    #we are making it column of new matrix
75    a.append(matrix1[j][i])
76  tr_matrix.append(a)
77
78print "Transpose of matrix 1 is",tr_matrix
79