Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python Matrix Operations with NumPy: Transpose, Addition, Multiplication & Slicing – A Practical Guide

Python Matrix Operations with NumPy

Mathematical modeling, scientific computing, and data analysis often rely on efficient manipulation of two‑dimensional data. In Python, matrices can be created with plain lists or, more powerfully, with the NumPy library. This guide walks you through the most common matrix operations, complete with clear code examples and best‑practice tips.

What is a Matrix?

A matrix is a rectangular array of numbers (or other data types) organized in rows and columns. While Python lacks a dedicated matrix type in its core language, you can represent one with nested lists or with NumPy’s ndarray, which offers fast, vectorized operations.

Creating a Matrix with Nested Lists

Nested lists are the simplest way to build a matrix. Each inner list represents a row:

# 3x3 matrix
M1 = [[8, 14, -6],
      [12, 7, 4],
      [-11, 3, 21]]
print(M1)

Output:

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

Reading Data

Access elements via row and column indices. To print the last element of each row:

for row in M1:
    print(row[-1])

Output:

-6
4
21

Adding Matrices

When both matrices share the same shape, element‑wise addition is straightforward:

M2 = [[3, 16, -6],
      [9, 7, -4],
      [-1, 3, 13]]

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

Output:

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

Element‑wise Multiplication

Similarly, you can multiply corresponding elements:

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

Output:

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

Using NumPy for Efficient Matrix Operations

NumPy provides a dedicated array type and a wealth of vectorized operations. Install it with pip install numpy and import it as np:

import numpy as np

Creating a Matrix

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

Output:

[[  5 -10  15]
 [  3  -6   9]
 [ -4   8  12]]

Basic Operations

Example: Matrix Dot Product

M1 = np.array([[3, 6], [5, -10]])
M2 = np.array([[9, -18], [11, 22]])
print(M1.dot(M2))

Output:

[[  93   78]
 [- 65 -310]]

Slicing

Slice rows and columns with array[row_start:row_end, col_start:col_end]:

M = np.array([[2, 4, 6, 8, 10],
              [3, 6, 9, -12, -15],
              [4, 8, 12, 16, -20],
              [5, -10, 15, -20, 25]])

print(M[1:3, 1:4])  # rows 1–2, columns 1–3
print(M[:, 3])      # all rows, 4th column
print(M[:1, :])     # first row, all columns
print(M[:3, :2])    # first 3 rows, first 2 columns

Output:

[[ 6  9 -12]
 [ 8 12  16]]
[  8 -12  16 -20]
[[ 2  4  6  8 10]]
[[ 2  4]
 [ 3  6]
 [ 4  8]]

Accessing Rows and Columns

# Rows
print(M[0])          # first row
print(M[-1])         # last row

# Columns
print(M[:, 0])       # first column
print(M[:, -1])      # last column

Key Takeaways

Python

  1. Python Print() Function: A Practical Guide with Examples
  2. Python Arrays: Creation, Manipulation, and Advanced Operations – Expert Guide
  3. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  4. Master Python `format()` Strings with Clear Examples
  5. Python round() Function Explained with Practical Examples
  6. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  7. Python timeit() – Measuring Execution Time with Practical Examples
  8. SciPy in Python: A Comprehensive Tutorial on Libraries & Functions
  9. Python list.count(): Expert Guide with Practical Examples
  10. Python Module Importing – A Practical Guide with Examples