Vector and Matrix Operations
using Lists and Arrays
Vector Operations
• List can be used for representing vectors (1-D
array).
• Addition of vectors
V1= 4 1 2 V2= 3 5 7
V3= V1+V2= 7 6 9
Vector Operations
• Dot (scalar) product of vectors
V1= 4 1 2 V2= 3 5 7
V3= V1.V2= 31
Vector Operations
• Cross product of vectors
V1= 4 1 2 V2= 3 5 7
V3= V1xV2= -3 -22 17
Matrix Operations
• Matrix can be represented as list of list
For example a 3x3 matrix may be represented as
[[a1 a2 a3 ] [b1 b2 b3] [c1 c2 c3]]
Row 1 Row 2 Row 3
A nxm matrix may be represented as
[[a11 a12 ... a1m] [a21 a22 ... a2m] ... [an1 an2 ... anm]]
Row 1 Row 2 Row n
Matrix Multiplication
A B Specification
0 1 2 3
0,j 0 n-1
i i,0 i,1 i,2 i,3
× 1,j 1 Ci,j = Σ Ai,k Bk,j
2,j 2 k=0
3,j 3
j Implementation
k=0 k=1 k=2 k=3
i,j C
=
Dot product approach
Courtesy Prof PR Panda CSE Department IIT Dehi
Matrix Multiplication
A B
0 1 2 3
0,j 0
i i,0 i,1 i,2 i,3 1,j 1 i,j
× = C
2,j 2
3,j 3
j
k=0 k=1 k=2 k=3
def mult(A,B,n,p,m):
C=[[0 for col in range(m)] for row in range(n)] DotProduct
for i in range(n):
for j in range(m):
for k in range(p):
C[i][j]+=A[i][k]*B[k][j]
return IIT
Courtesy Prof PR Panda CSE Department C Dehi
Matrix Multiplication
def mult(A,B,n,p,m):
C=[[0 for col in range(m)] for row in range(n)]
for i in range(n):
for j in range(m):
for k in range(p):
C[i][j]+=A[i][k]*B[k][j]
return C
def mult(A,B,n,p,m):
C=[[0 for col in range(m)] for row in range(n)]
for i in range(n):
for j in range(m):
t=0 Better Version!
for k in range(p):
Less memory
t+=A[i][k]*B[k][j]
access time
C[i][j]=t
return C
Matrix Transpose
def transpose(A,n,m):
AT=[[0 for col in range(n)] for row in range(m)]
for i in range(n):
for j in range(m):
AT[j][i]=A[i][j]
return AT
NumPy Package
• NumPy is a Python package for numerical
computation
• NumPy core data type is array
• NumPy must be installed if to be used
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a*b
array([ 4, 10, 18])
NumPy Package
• NumPy is a Python package for numerical
computation
• NumPy core data type is array
• NumPy must be installed if to be used
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.dot(a,b)
32