Topics to Cover
Class 1: (Linear Array)
● What is an Array? Difference with other data structures.
● A sequence of data with the same type
● Why need an Array if a list can already do most of the tasks?
● NumPy Array (zeros)
● indexing (same as list and string)Why size can not be changed?
● benefits of array (random access)
● selection/bubble sort
Class 2: (Multidimensional Array)
● Cubic array example??
● Real life example (Matrix-2D Array), Higher Dimensional-3D (seat placement in a classroom)
● Matrix-matrix multiplication,
● vector-vector, matrix-vector, matrix row switch (For student’s self study)
1
Linear Array
Array
● Sequence of data
● Single data type
● Fixed length
● Indexed
● Fixed-dimensional
2
Linear Array
Difference between Array and List
List Array
Can store different types of data A single type of data
Dynamic and mutable Fixed length and mutable
Comparatively slower Fast because has contiguous memory
allocation
As data is stored in discontinuous As memory is contagious internal
memory space the internal memory memory allocation is simple. One data
allocation is complex. is stored after another.
It is easy to append elements to a It is easy perform arithmetic
list. operations on arrays.
3
Linear Array
Introduction to NumPy
Array is not native to python, so we use a library called numpy
● Library import
import numpy as np
● Array creation
arr = np.zeros(size, dtype = datatype) arr = np.zeros(5, dtype = int)
(dtype is float by default)
● Array length
○ .size : attribute, returns the total number of
elements irrespective of dimensionality.
print(len(arr)) 5
○ len() : function, returns the total number of print(arr.size) 5
elements along the first dimension
4
Linear Array
Array Operations
● Read and Write
var = arr[2] #read
arr[3] = 10 #write
● Array traversal
idx = 0 for idx in range(arr.size):
while idx < arr.size: print(arr[idx])
print(arr[idx])
idx += 1
5
Linear Array
Array Operations
● Array creation from user input length = int(input("Enter array length: "))
arr = np.zeros(length, dtype = int)
○ Can be created from a single for i in range(length):
input string as well value = int(input("Enter a value: "))
arr[i] = value
print(arr)
● Array Manipulation
○ Updating values
○ Operation using/on indices
○ Array size increment => Creating a new array with increase size and copied values
6
Linear Array
Benefits of Array
● Memory Efficient
● Random Access
● Faster Performance
● Better suited for Mathematical Operations (i.e. vectorized/matrix
operations)
7
Linear Array
Bubble Sort
1st Pass 3rd Pass
-2 45 0 11 -9 -2 0 -9 11 45 arr = np.array([-2, 45, 0, 11, -9])
for i in range(len(arr)):
-2 0 45 11 -9 -2 -9 0 11 45
for j in range(0, len(arr) - i - 1):
-2 0 11 45 -9 if arr[j] > arr[j + 1]:
4th Pass
temp = arr[j]
-2 0 11 -9 45
-2 -9 0 11 45 arr[j] = arr[j+1]
arr[j+1] = temp
2nd Pass -9 -2 0 11 45
print(arr)
-2 0 11 -9 45
-2 0 -9 11 45
8
Multi-Dimensional Array
Multi Dimensional Array
We can start by discussing from Vector to Matrix then Tensor.
9
Multi-Dimensional Array
1D, 2D and 3D array
10
Multi-Dimensional Array
RGB image
A RGB image is actually a
3D array containing three
2D Matrices for Red, Green
and Blue values.
11
Multi-Dimensional Array
Matrix/2D Array Examples
● Seating Arrangement in a classroom.
● Linear Algebra Usage (Matrix representation).
● Displays are 2D array of pixels.
2D MATRIX
Dimensions of matrices
Rows x Columns
12
Multi-Dimensional Array
2D Matrix in Python using Numpy
import numpy as np
arr2D = np.zeros(shape=(row,col), dtype = datatype)
arr2D = np.zeros(shape=(3,4), dtype = int) Output
print(arr2D) [[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
arr2D = np.zeros(shape=(3,4), dtype = float) Output
print(arr2D) [[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
arr2D = np.zeros(shape=(3,4), dtype = str) Output
print(arr2D) [['' '' '' '']
['' '' '' '']
['' '' '' '']]
13
Multi-Dimensional Array
2D Matrix from Python List using Numpy
arr2D=np.array( [[1,2,4,6],[5,7,9,8]] ) Output
print(arr2D) [[1 2 4 6]
print(arr2D.dtype) [5 7 9 8]]
int64
arr2D=np.array( [[1,2,4.2,6],[5,7,9,8]] ) Output
print(arr2D) [[1. 2. 4.2 6. ]
print(arr2D.dtype) [5. 7. 9. 8. ]]
float64
14
Multi-Dimensional Array
Indexing in 2D Matrix a
● a[row_num] will give us a
single linear array.
● a[row_num][col_num] can
access individual cell.
a = np.array( [[1,2,4,6],[5,6,7,8],[9,0,1,2]] ) Output
print(a) [[1 2 4 6]
print("First Row", a[0]) [5 6 7 8]
print("Second Row", a[1])
[9 0 1 2] ]
print("Third Cell", a[0][2])
First Row [1 2 4 6]
Second Row [5 6 7 8]
Third Cell 4 15
Multi-Dimensional Array
Accessing the shape and size of a 2D Matrix
arr2D = np.zeros(shape=(3,4), dtype = int) Output
print(arr2D) [[0 0 0 0]
row, col = arr2D.shape[0], arr2D.shape[1] [0 0 0 0]
total_cells = arr2D.size [0 0 0 0]]
print(“Row Amount”, row) Row Amount 3
print(“Column Amount”, col) Column Amount 4
print(“Total cells”, total_cells)
Total cells 12
16
Multi-Dimensional Array
Iteration of 2D Matrix
arr=np.array( [[1,2,4,6],[5,7,9,8]] ) Output
r_len , c_len = arr.shape[0], arr.shape[1] 1 2 4 6
#The Outer loop iterates rows 5 7 9 8
for r in range(r_len):
#The inner loop iterates column of each row
for c in range(c_len):
print(arr[r][c],end=' ')
print()
17
Multi-Dimensional Array
Scalar & Matrix Multiplication
A=np.array( [[0,2,3],[1,1,0]] ) Output
print("Before",A) Before:
r_len , c_len = A.shape[0], A.shape[1] [[0 2 3]
#The outer loop iterates rows [1 1 0]]
for r in range(r_len): After:
#The inner loop iterates column of each row [[0 4 6]
[2 2 0]]
for c in range(c_len):
A[r][c] = 2*A[r][c]
print("After",A)
18
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
n=3
= = 1x2 + 2x6 + 1x1
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Multi-Dimensional Array
Matrix Multiplication Visual m=3
p=4
=
Matrix & Matrix Multiplication Code Multi-Dimensional Array
A=np.array( [[0,5],[1,2],[3,4]] ) OUTPUT
B=np.array( [[3,2,1],[1,2,4]] )
print("A(3,2):") A(3,2):
print(A) [[0 5]
print("B(2,3):") [1 2]
print(B) [3 4]]
Ar_len , Ac_len = A.shape[0], A.shape[1]
Br_len , Bc_len = B.shape[0], B.shape[1] B(2,3):
#Here, Bc_len==1 and Ac_len==Br_len [[3 2 1]
C=np.zeros( shape=(Ar_len,Bc_len), dtype=int) [1 2 4]]
Cr_len, Cc_len = C.shape[0], C.shape[1]
for i in range(Cr_len): A X B = C(3,3):
for j in range(Cc_len): [[ 5 10 20]
sum=0 [ 5 6 9]
for k in range(Br_len): [13 14 19]]
sum += A[i][k] * B[k][j]
C[i][j] = sum
print("A X B = C(3,3):")
print(C) 26
Rest of the parts won’t be covered in class.
Consider them as practice problems
27
Multi-Dimensional Array
Matrix & Vector Multiplication Visual
28
Matrix & Vector Multiplication Code Multi-Dimensional Array
A=np.array( [[0,5],[1,2],[3,4]] ) :OUTPUT:
B=np.array( [[3],[2]] )
print("A(3,2):") A(3,2):
print(A) [[0 5]
print("B(2,1):") [1 2]
print(B) [3 4]]
Ar_len , Ac_len = A.shape[0], A.shape[1]
Br_len , Bc_len = B.shape[0], B.shape[1] B(2,1):
#Here, Bc_len==1 and Ac_len==Br_len [[3]
C=np.zeros( shape=(Ar_len,Bc_len), dtype=int) [2]]
Cr_len, Cc_len = C.shape[0], C.shape[1]
for i in range(Cr_len): C(3,1):
for j in range(Cc_len): [[10]
sum=0 [ 7]
for k in range(Br_len): [17]]
sum += A[i][k] * B[k][j]
C[i][j] = sum
#Here, j will be 0 since Cc_len==Bc_len==1
print("C(3,1):") 29
print(C)
Multi-Dimensional Array
import numpy as np
A=np.array( [[3,4], A(3,2):
[4,5], [[3 4]
[10,11]] ) [4 5]
# The shape of A is (3,2) [10 11]]
B=np.array( [3,2] )
# The shape of A is (2,1) B(2,1):
# So, the shape of C will be (3,1) [3
C=np.zeros( shape=(3,1), dtype=int) 2]
for i in range(3):
sum=0 C(3,1):
for j in range(2): [[17]
sum += A[i][j] * B[j] [22]
[52]]
C[i][0]=sum
print("\nC(3,1):")
print(C)
30
Multi-Dimensional Array
Vector & Vector Dot Product Code
v1 = np.array([2,3,1]) OUTPUT
v2 = np.array([5,-2,11])
Dot product: 15
dot_product = 0
for i in range(v1.size):
dot_product+= v1[i]*v2[i]
print(f'Dot product: {dot_product}')
31
Multi-Dimensional Array
Matrix Row Switching v1
A = np.array([[4,3,2],[7,1,5],[-1,0,10]]) OUTPUT:
print('Before Switching')
Before Switching
print(A)
[[ 4 3 2]
#Switching row 2 and row 1 [ 7 1 5]
A[[1,2]] = A[[2,1]] [-1 0 10]]
print('After Switching')
After Switching
print(A)
[[ 4 3 2]
[-1 0 10]
[ 7 1 5]]
32
Multi-Dimensional Array
Matrix Row Switching v2
A = np.array([[4,3,2],[7,1,5],[-1,0,10]]) OUTPUT:
print('Before Switching')
Before Switching
print(A)
[[ 4 3 2]
#Switching row 1 and row 2 [ 7 1 5]
#Backing up row 1 by creating a new array [-1 0 10]]
temp = np.array(A[1])
After Switching
#putting row 2 in row 1
[[ 4 3 2]
A[1] = A[2] [-1 0 10]
#putting row backup (row 2) in row 1 [ 7 1 5]]
A[2] = temp
print('After Switching')
print(A)
33
Matrix Row Switching v3 Multi-Dimensional Array
A = np.array([[4,3,2],[7,1,5],[-1,0,10]]) OUTPUT:
print('Before Switching')
Before Switching
print(A)
[[ 4 3 2]
row_len = A.shape[0] [ 7 1 5]
col_len = A.shape[1] [-1 0 10]]
#Switching Row index 1 and Row index 2
After Switching
for c in range(col_len):
[[ 4 3 2]
temp = A[1][c] [-1 0 10]
A[1][c] = A[2][c] [ 7 1 5]]
A[2][c] = temp
print("After Switching")
print(A)
34