---Advertisement---

Python Matrix Operations: Transpose, Multiplication, and NumPy Best Examples 2025

By Bhavani

Updated On:

---Advertisement---
Python Matrix Operations

Python Matrix Operations: A Python matrix is a two-dimensional rectangular data structure stored in rows and columns. It can contain numbers, strings, or expressions and is widely used for mathematical and scientific calculations.

👉Python Matrix Operations: Python does not have a direct matrix data type. However, matrices can be created using:

  1. Nested Lists
  2. NumPy Arrays

Example of a 3×3 matrix using nested lists:

python

M1 = [[8, 14, -6], 

      [12, 7, 4], 

      [-11, 3, 21]]

print(M1)

lua

[[8, 14, -6], [12, 7, 4], [-11, 3, 21]]

To read the last element from each row:

python

for row in M1:

    print(row[-1])

diff

-6  

4  

21  

python

for row in M1:

    print(row)

css

[8, 14, -6]  

[12, 7, 4]  

[-11, 3, 21]  


Example:

python

M1 = [[8, 14, -6], 

      [12, 7, 4], 

      [-11, 3, 21]]

M2 = [[3, 16, -6], 

      [9, 7, -4], 

      [-1, 3, 13]]

M3 = [[M1[i][j] + M2[i][j] for j in range(len(M1[0]))] for i in range(len(M1))]

print(“Sum of Matrix M1 and M2:”, M3)

lua

[[11, 30, -12], [21, 14, 0], [-12, 6, 34]]


Example:

python

M3 = [[M1[i][j] * M2[i][j] for j in range(len(M1[0]))] for i in range(len(M1))]

print(“Multiplication of Matrix M1 and M2:”, M3)

lua

[[24, 224, 36], [108, 49, -16], [11, 9, 273]]


NumPy simplifies matrix operations and improves performance. Install NumPy using:

nginx

pip install numpy

Import NumPy in your code:

python

import numpy as np

python

M1 = np.array([[5, -10, 15], [3, -6, 9], [-4, 8, 12]])

print(M1)

lua

[[  5 -10  15]  

 [  3  -6   9]  

 [ -4   8  12]]  


python

M1 = np.array([[3, 6, 9], [5, -10, 15], [-7, 14, 21]])

M2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])

M3 = M1 + M2

print(M3)

lua

[[ 12 -12  36]  

 [ 16  12  48]  

 [  6 -12  60]]


python

M3 = M1 – M2

print(M3)

lua

[[-6  24 -18]  

 [-6 -32 -18]  

 [-20  40 -18]]


python

M1 = np.array([[3, 6], [5, -10]])

M2 = np.array([[9, -18], [11, 22]])

M3 = np.dot(M1, M2)

print(M3)

lua

[[ 93  78]  

 [-65 -310]]


python

M1 = np.array([[3, 6, 9], [5, -10, 15], [4, 8, 12]])

M2 = M1.transpose()

print(M2)

lua

[[  3   5   4]  

 [  6 -10   8]  

 [  9  15  12]]


Example:

python

M1 = np.array([[2, 4, 6, 8, 10], 

               [3, 6, 9, -12, -15],

               [4, 8, 12, 16, -20],

               [5, -10, 15, -20, 25]])

print(M1[1:3, 2:4])  # Slicing rows 1-2 and columns 2-3

lua

[[  9 -12]  

 [ 12  16]]

Facebook Login Automation Using Python

Download Python

Leave a Comment

Index