Numpy
Vector creation
python
import numpy as np
a = np.zeros(4);
# a = [0. 0. 0. 0.]
a = np.random.random_sample(4)
# [0.79854204 0.53395596 0.42365001 0.52982915]
Vector indexing
python
a = np.arange(10)
# [0 1 2 3 4 5 6 7 8 9]
a[2] # 2
a[-1] # 9
Slicing
python
#vector slicing operations
a = np.arange(10)
# a = [0 1 2 3 4 5 6 7 8 9]
#access 5 consecutive elements (start:stop:step)
c = a[2:7:1]; # [2 3 4 5 6]
# access 3 elements separated by two
c = a[2:7:2]; # [2 4 6]
# access all elements index 3 and above
c = a[3:]; # [3 4 5 6 7 8 9]
# access all elements below index 3
c = a[:3]; # [0 1 2]
# access all elements
c = a[:]; # [0 1 2 3 4 5 6 7 8 9]
Single vector operations
python
a = np.array([1,2,3,4])
# [1 2 3 4]
b = -a
# [-1 -2 -3 -4]
# sum all elements of a, returns a scalar
b = np.sum(a)
# 10
b = np.mean(a)
# 2.5
b = a**2
# [ 1 4 9 16]
Vector dot product
python
# test 1-D
a = np.array([1, 2, 3, 4])
b = np.array([-1, 4, 3, 2])
c = np.dot(a, b)
print(f"NumPy 1-D np.dot(a, b) = {c}, np.dot(a, b).shape = {c.shape} ")
c = np.dot(b, a)
print(f"NumPy 1-D np.dot(b, a) = {c}, np.dot(a, b).shape = {c.shape} ")
# NumPy 1-D np.dot(a, b) = 24, np.dot(a, b).shape = ()
# NumPy 1-D np.dot(b, a) = 24, np.dot(a, b).shape = ()
Matrix creation
python
a = np.zeros((1, 5))
print(f"a shape = {a.shape}, a = {a}")
a = np.zeros((2, 1))
print(f"a shape = {a.shape}, a = {a}")
a = np.random.random_sample((1, 1))
print(f"a shape = {a.shape}, a = {a}")
# a shape = (1, 5), a = [[0. 0. 0. 0. 0.]]
# a shape = (2, 1), a = [
# [0.],
# [0.]]
# a shape = (1, 1), a = [[0.44236513]]
Matrix operations
python
a = np.arange(6).reshape(-1, 2)
#reshape is a convenient way to create matrices
print(f"a.shape: {a.shape}, \na= {a}")
# a.shape: (3, 2),
# a= [[0 1]
# [2 3]
# [4 5]]
Matrix slicing
python
#vector 2-D slicing operations
a = np.arange(20).reshape(-1, 10)
# a =
# [[ 0 1 2 3 4 5 6 7 8 9]
# [10 11 12 13 14 15 16 17 18 19]]
#access 5 consecutive elements (start:stop:step)
print("a[0, 2:7:1] = ", a[0, 2:7:1], ", a[0, 2:7:1].shape =", a[0, 2:7:1].shape, "a 1-D array")
# a[0, 2:7:1] = [2 3 4 5 6] , a[0, 2:7:1].shape = (5,) a 1-D array
#access 5 consecutive elements (start:stop:step) in two rows
print("a[:, 2:7:1] = \n", a[:, 2:7:1], ", a[:, 2:7:1].shape =", a[:, 2:7:1].shape, "a 2-D array")
# a[:, 2:7:1] =
# [[ 2 3 4 5 6]
# [12 13 14 15 16]] , a[:, 2:7:1].shape = (2, 5) a 2-D array
# access all elements
print("a[:,:] = \n", a[:,:], ", a[:,:].shape =", a[:,:].shape)
# a[:,:] =
# [[ 0 1 2 3 4 5 6 7 8 9]
# [10 11 12 13 14 15 16 17 18 19]] , a[:,:].shape = (2, 10)
# access all elements in one row (very common usage)
print("a[1,:] = ", a[1,:], ", a[1,:].shape =", a[1,:].shape, "a 1-D array")
# a[1,:] = [10 11 12 13 14 15 16 17 18 19] , a[1,:].shape = (10,) a 1-D array
# same as
print("a[1] = ", a[1], ", a[1].shape =", a[1].shape, "a 1-D array")
# a[1] = [10 11 12 13 14 15 16 17 18 19] , a[1].shape = (10,) a 1-D array