1
+ import numpy as np
2
+ # import time
3
+
4
+ """
5
+ This program works (with both the functions being active) very well for square matrices.
6
+ For non-square matrices, be careful to check the shape compatibility of the matricess involved.
7
+ NOTE: This is a brute-force implementation. There are more efficient algorithms for operating on matrices.
8
+ """
9
+
10
+ def MatrixAddition (matrix_a , matrix_b ):
11
+ m ,n = matrix_a .shape
12
+ matrix_c = [[0 for i in range (m )] for j in range (n )]
13
+ for i in range (m ):
14
+ for j in range (n ):
15
+ matrix_c [i ][j ] += matrix_a [i ][j ] + matrix_b [i ][j ]
16
+ return np .array (matrix_c )
17
+
18
+ def MatrixMultiplication (matrix_a , matrix_b ):
19
+ m ,n = matrix_a .shape
20
+ n ,p = matrix_b .shape
21
+ matrix_c = [[0 for i in range (m )] for j in range (n )]
22
+ for i in range (m ):
23
+ for j in range (p ):
24
+ for k in range (n ):
25
+ matrix_c [i ][j ] += matrix_a [i ][k ]* matrix_b [k ][j ]
26
+ return np .array (matrix_c )
27
+
28
+ a1 = int (input ("Enter how many rows in the first matrix: " ))
29
+ b1 = int (input ("Enter how many columns in the first matrix: " ))
30
+
31
+ a2 = int (input ("Enter how many rows in the second matrix: " ))
32
+ b2 = int (input ("Enter how many columns in the second matrix: " ))
33
+ print ("\n " )
34
+ first_matrix = [[0 for i in range (a1 )] for j in range (b1 )]
35
+ for i in range (a1 ):
36
+ for j in range (b1 ):
37
+ first_matrix [i ][j ] += int (input ("first_matrix[" + str (i )+ "][" + str (j )+ "]: " ))
38
+ first_matrix = np .array (first_matrix )
39
+ print ("\n " )
40
+ second_matrix = [[0 for i in range (a2 )] for j in range (b2 )]
41
+ for i in range (a2 ):
42
+ for j in range (b2 ):
43
+ second_matrix [i ][j ] += int (input ("second_matrix[" + str (i )+ "][" + str (j )+ "]: " ))
44
+ second_matrix = np .array (second_matrix )
45
+
46
+ print ("\n " )
47
+
48
+ print ("The first matrix given is: \n " , first_matrix )
49
+ print ("The second matrix given is: \n " , second_matrix )
50
+
51
+ # resultant_sum_matrix = MatrixAddition(first_matrix, second_matrix)
52
+ # print("The sum of the given matrices is:")
53
+ # time.sleep(0.5)
54
+ # print(resultant_sum_matrix)
55
+
56
+ resultant_product_matrix = MatrixMultiplication (first_matrix , second_matrix )
57
+ print ("The product of the given matrices is: " )
58
+ # time.sleep(0.5)
59
+ print (resultant_product_matrix )
0 commit comments