forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
How to use matrices in Python
55 lines (39 loc) · 1.11 KB
/
How to use matrices in Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#In python, matrices are represented as follows:
identity = [[1, 0],
[0, 1]]
#To add matrices:
matrix_one = [[2, 3, 4],
[10,11,12],
[6,7,8]]
matrix_two = [[3, 9, 12],
[9,11,14],
[1,7,16]]
matrix_three= [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(matrix_one)
for i in range(len(matrix_one)):
for k in range(len(matrix_two)):
matrix_three[i][k] = matrix_one[i][k] + matrix_two[i][k]
print(matrix_three)
#To multiply matrices:
matrix_one = [[2, 3, 4],
[10,11,12],
[6,7,8]]
matrix_two = [[3, 9, 12],
[9,11,14],
[1,7,16]]
matrix_three= [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(matrix_one)
for i in range(len(matrix_one)):
for k in range(len(matrix_two)):
matrix_three[i][k] = matrix_one[i][k] * matrix_two[i][k]
print(matrix_three)
#Using a NumPy array
import numpy as np
matrix_one = np.array([[2, 3, 4], [10,11,12], [6,7,8]])
matrix_two = np.array([[3, 9, 12], [9,11,14], [1,7,16]])
matrix_three = matrix_one + matrix_two
matrix_four = matrix_one*matrix_two