
👉Python Matrix Operations
👉What is a Python Matrix?
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.
👉How to Create a Matrix in Python
👉Python Matrix Operations: Python does not have a direct matrix data type. However, matrices can be created using:
- Nested Lists
- NumPy Arrays
👉Creating a Python Matrix Operations Using Nested Lists
Example of a 3×3 matrix using nested lists:
python
M1 = [[8, 14, -6],
[12, 7, 4],
[-11, 3, 21]]
print(M1)
👉Python Matrix Operations Output:
lua
[[8, 14, -6], [12, 7, 4], [-11, 3, 21]]
👉Reading Data from a Python Matrix
To read the last element from each row:
python
for row in M1:
print(row[-1])
👉Output:
diff
-6
4
21
👉Printing Each Row in the Matrix
python
for row in M1:
print(row)
👉Output:
css
[8, 14, -6]
[12, 7, 4]
[-11, 3, 21]
👉Adding Matrices Using Nested Lists
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)
👉Output:
lua
[[11, 30, -12], [21, 14, 0], [-12, 6, 34]]
👉Multiplying Matrices Using Nested Lists
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)
👉Output:
lua
[[24, 224, 36], [108, 49, -16], [11, 9, 273]]
👉Creating a Python Matrix Using NumPy
NumPy simplifies matrix operations and improves performance. Install NumPy using:
nginx
pip install numpy
Import NumPy in your code:
python
import numpy as np
👉Example: Creating a Matrix Using NumPy
python
M1 = np.array([[5, -10, 15], [3, -6, 9], [-4, 8, 12]])
print(M1)
👉Output:
lua
[[ 5 -10 15]
[ 3 -6 9]
[ -4 8 12]]
👉Matrix Operations Using NumPy
👉Matrix Addition
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)
👉Output:
lua
[[ 12 -12 36]
[ 16 12 48]
[ 6 -12 60]]
👉Matrix Subtraction
python
M3 = M1 – M2
print(M3)
👉Output:
lua
[[-6 24 -18]
[-6 -32 -18]
[-20 40 -18]]
👉Matrix Multiplication Using np.dot()
python
M1 = np.array([[3, 6], [5, -10]])
M2 = np.array([[9, -18], [11, 22]])
M3 = np.dot(M1, M2)
print(M3)
👉Output:
lua
[[ 93 78]
[-65 -310]]
👉Matrix Transpose
python
M1 = np.array([[3, 6, 9], [5, -10, 15], [4, 8, 12]])
M2 = M1.transpose()
print(M2)
👉Output:
lua
[[ 3 5 4]
[ 6 -10 8]
[ 9 15 12]]
👉Slicing a Matrix
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
👉Output:
lua
[[ 9 -12]
[ 12 16]]