-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linear_Algebra_with_numpy.py
82 lines (60 loc) · 2.09 KB
/
Linear_Algebra_with_numpy.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'''In the upcoming weeks you will have to implement different assignments in Python. For linear algebra calculations
in Python you can use NumPy. We provide a subset of the NumPy functionality, which is sufficient to solve the
different tasks. A complete list of the supported functions can be found in the wiki. If you find errors in the
behavior of our NumPy implementation feel free to post them in the forum.
In the code editor below you find a couple of examples demonstrating basic linear algebra calculations in NumPy.'''
import numpy as np
def run():
# create a column vector
col_vec = np.array([[1], [2]])
print "column vector"
print col_vec
# create a row vector
row_vec = np.array([[1, 2]])
print "row vector"
print row_vec
# create a matrix
mat = np.array([[1, 2], [3, 4]])
print "matrix"
print mat
# inspect dimensions
print "row vector dimensions", row_vec.ndim
shape = row_vec.shape
print "row vector rows", shape[0], "columns", shape[1]
print "matrix dimensions", mat.ndim
shape = mat.shape
print "matrix rows", shape[0], "columns", shape[1]
# transpose
vec_t = row_vec.transpose() # or row_vec.T
print "transposed vector"
print vec_t
mat_t = mat.transpose() # or mat.T
print "transposed matrix"
print mat_t
a = np.array([[2], [-4], [1]])
b = np.array([[2], [1], [-2]])
# addition
print "a + b"
print a + b
# subtraction
print "a - b"
print a - b
# scalar multiplication
print "1.2 * a"
print 1.2 * a
# element wise multiplication
print "a * b"
print a * b
# vector scalar product
print "a . b"
print np.dot(a.transpose(), b)
# vector cross product
print "a x b"
print np.cross(a, b, axis=0) # or np.cross(a.T, b.T).T
identity = np.array([[1, 0], [0, 1]])
# matrix vector product
print "identity . col_vec"
print np.dot(identity, col_vec)
# matrix product
print "identity . mat"
print np.dot(identity, mat)