Linear Algebra With Python 1 – Basic Operations

NumPy arrays offer powerful operations for multidimensional data. Shape reveals array dimensions. Addition, subtraction, and scalar multiplication are element-wise. Matrix multiplication uses np.dot(). Transpose flips rows and columns. Several methods exist to check array equality, including array_equal(), all(), allclose(), and array_equiv().

Shape

>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> b = np.array([[7, 8, 9, 23], [10, 11, 12, 1]])
>>> a.shape
(2, 3)
>>> b.shape
(2, 4)

Addition And Scalar

>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> b = np.array([[7, 8, 9], [10, 11, 12]])
       
>>> a + b
array([[ 8, 10, 12],
       [14, 16, 18]])
>>> a - b
array([[-6, -6, -6],
       [-6, -6, -6]])
       
>>> 5 * a
array([[ 5, 10, 15],
       [20, 25, 30]])     

Multiplication

>>> a = np.array([[1, 2, 5], [4, 5, 9]])
>>> b = np.array([[1, 0, 1, 2], [2, 1, 4, 3], [5, 1, 0, 6]])
>>> np.dot(a, b)
array([[20,  5,  9, 26],
       [44, 11, 24, 59]])

Transpose

>>> a = np.array([[1, 2, 5], [4, 5, 9]])
>>> a.T
array([[1, 4],
       [2, 5],
       [5, 9]])

Check two matrix equal or not


>>> a = np.array([1, 2, 5, 7])
>>> b = np.array([1, 2, 5, 7])
# Method 1: use array_equal()
>>> np.array_equal(a, b)
True
# Method 2: use == operator and all()
>>> print((a == b).all())
True
# Method 3: use numpy.allcloses()
>>> np.allclose(a, b)
True
# Method 4: user numpy.array_equiv()
>>> np.array_equiv(a, b)
True

πŸš€ Unlock Ads-Free Experience At $5/year

βœ“ 14 days free trial βœ“ Cancel anytime

6 thoughts on “Linear Algebra With Python 1 – Basic Operations”

Leave a Comment

Your email address will not be published. Required fields are marked *