import numpy as np

Exercises

1. Dot product of two vectors

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
 
# Expected Output:
# 32
np.einsum("i,i", a, b)
32

2. Matrix vector multiplication

M = np.array([
    [1, 2],
    [3, 4],
    [5, 6]])
v = np.array([7, 8])
 
# Expected Output:
# array([23, 53, 83])
3 x 2, 1 x 2
np.einsum("ij,j->i", M, v)
array([23, 53, 83])

3. Matrix Matrix multiplication

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
 
# Expected Output:
# array([[19, 22],
#        [43, 50]])
 
np.einsum("ij,jk->ik", A, B)
array([[19, 22],
       [43, 50]])

4. Outer product of vectors

x = np.array([1, 2, 3])
y = np.array([4, 5])
 
# Expected Output:
# array([[ 4,  5],
#        [ 8, 10],
#        [12, 15]])
np.einsum("i,j->ij", x, y)
array([[ 4,  5],
       [ 8, 10],
       [12, 15]])
result = np.zeros((x.shape[0], y.shape[0]), dtype=x.dtype)
for i in range(x.shape[0]):
    for j in range(y.shape[0]):
        result[i,j] = x[i] * y[j]
result
array([[ 4,  5],
       [ 8, 10],
       [12, 15]])

5. Trace of Matrix

Trace is sum of diagnol of matrix

A = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
 
# Expected Output:
# 15
 
print(np.trace(A))
 
print(np.einsum("ii", A))
15
15

6. Sum over all elements of matrix

A = np.array([[1, 2],
              [3, 4]])
 
# Expected Output:
# 10
 
print(np.sum(A))
print(np.einsum("ij->", A))
10
10
result = 0
for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        result += A[i,j]
result
10