```python
import numpy as np
A = np.random.rand(3,5)
A = np.arange(15).reshape(3,5)
B = np.random.rand(5,2)
B = np.arange(10).reshape(5,2)
M = np.empty((3,2))

# M_{ij} - \sum_{k} A_{ik}*B_{kj} = A_{i,}*B_{kj}
for i in range(3):
    for j in range(2):
        total = 0
        for k in range(5):
            total += A[i,k]*B[k,j]
        M[i,j] = total
M 
```




    array([[ 60.,  70.],
           [160., 195.],
           [260., 320.]])




```python
# ik is A index
# kj is B index
# ij is outptu index
# i j is free index
# k is dummy index
#### repeating letter in a different term
####   will be multiplied and will be the output.
####   mulipied summation 
# M_{ik} = A_{ik}B_{kj}
np.einsum('ik,kj->ij',A,B)
```




    array([[ 60,  70],
           [160, 195],
           [260, 320]])




```python
a = np.arange(5)
b = np.arange(3)
# free index: i,j(Used in output)
# Summation(dummy) index: None (All used in output)
# outer[i,j] = a[i] * b[j]
np.einsum('i,j->ij',a,b)
```




    array([[0, 0, 0],
           [0, 1, 2],
           [0, 2, 4],
           [0, 3, 6],
           [0, 4, 8]])




```python
outer_product = np.empty((5,3))
for i in range(5):
    for j in range(3):
        total = 0
        total += a[i]*b[j]
        outer_product[i,j] = total
outer_product
```




    array([[0., 0., 0.],
           [0., 1., 2.],
           [0., 2., 4.],
           [0., 3., 6.],
           [0., 4., 8.]])




```python
# Ommiting a letter measn that axis will be summed.
# \sum_{i}x[i]
x = np.ones(3)
np.einsum('i->',x)
```




    3.0




```python
x = np.arange(6).reshape(2,3)
np.einsum('ij->ji',x)

```




    array([[0, 2, 4],
           [1, 3, 5]])




```python
x
```




    array([[0, 1],
           [2, 3],
           [4, 5]])




```python
# Permutation of Tensors
np.einsum("ij->ji",x)
```




    array([[0, 2, 4],
           [1, 3, 5]])




```python
# Summation
np.einsum('ij->',x)
```




    15




```python
# column sum
np.einsum('ij->j',x)
```




    array([6, 9])




```python
# row sum
np.einsum('ij->i',x)
```




    array([1, 5, 9])




```python
# Matrix-Vector multiplication
v = np.arange(3)
# 3,2 -> 1,3
np.einsum('ij,i->ij',x,v)
```




    array([[ 0,  0],
           [ 2,  3],
           [ 8, 10]])




```python
x1 = np.arange(6).reshape(2,3)
# 2,3 -> 1,3
np.einsum('ij,k->ki',x1,v)
```




    array([[ 0,  0],
           [ 3, 12],
           [ 6, 24]])




```python
import sympy as sm
sm.Matrix(np.einsum('ij,jk->ik',x1,x))
```




$\displaystyle \left[\begin{matrix}10 & 13\\28 & 40\end{matrix}\right]$




```python

```


```python

```

bea43cd8694e4db447c183413cc87deb46f917a2
ipynb
Jupyter Notebook
python/Matrices/einsum.ipynb
karng87/nasm_game
a97fdb09459efffc561d2122058c348c93f1dc87
MIT
python/Matrices/einsum.ipynb
karng87/nasm_game
a97fdb09459efffc561d2122058c348c93f1dc87
MIT
python/Matrices/einsum.ipynb
karng87/nasm_game
a97fdb09459efffc561d2122058c348c93f1dc87
MIT
Qwen/Qwen-72B
1. YES
2. YES