Newaxis¶

In [1]:
%pip install numpy
import numpy as np
Requirement already satisfied: numpy in /home/samrat/Documents/numpy-torch-tutorials/venv/lib/python3.8/site-packages (1.24.4)
Note: you may need to restart the kernel to use updated packages.
In [4]:
A = np.random.randint(low=1, high=10, size=4)
B = np.random.randint(low=1, high=10, size=3)
A, B
Out[4]:
(array([6, 9, 6, 3]), array([9, 6, 6]))
In [9]:
A = A[:, np.newaxis]
B = B[np.newaxis, :]
A, B
Out[9]:
(array([[[6]],
 
        [[9]],
 
        [[6]],
 
        [[3]]]),
 array([[9, 6, 6]]))
In [10]:
A - B
Out[10]:
array([[[-3,  0,  0]],

       [[ 0,  3,  3]],

       [[-3,  0,  0]],

       [[-6, -3, -3]]])