Labs ICT
Pro Login

Transpose & Inverse

Flipping and reversing matrices.

Transpose & Inverse

Transpose and inverse are like mirror images and undo buttons. Think of transpose as flipping a matrix over its diagonal, and inverse as finding the matrix that undoes multiplication.

Transpose with .T

The .T attribute flips rows and columns.


import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6]])
transposed = matrix.T

print(f"Original shape: {matrix.shape}")
print(f"Transposed shape: {transposed.shape}")
print(f"Original:\n{matrix}")
print(f"Transposed:\n{transposed}")
    

Notice how (2, 3) becomes (3, 2). Rows become columns and vice versa.

Inverse with np.linalg.inv

The inverse of a matrix A is A^-1 such that A @ A^-1 = Identity.


import numpy as np

A = np.array([[1, 2], [3, 4]])
A_inv = np.linalg.inv(A)

print(f"Matrix A:\n{A}")
print(f"Inverse:\n{A_inv}")
print(f"A @ A_inv:\n{A @ A_inv}")
    

Here is the thing - the result should be close to the identity matrix. Floating point errors make it not exact.

When Inverse Doesn't Exist

Singular matrices don't have inverses.


import numpy as np

singular = np.array([[1, 2], [2, 4]])
try:
    inv = np.linalg.inv(singular)
except np.linalg.LinAlgError:
    print("Matrix is singular, no inverse exists")
    

One thing that confused me at first was when a matrix is singular. It happens when rows/columns are linearly dependent.

Try it Yourself →

Key Takeaways

  • .T transposes a matrix (swaps rows and columns)
  • np.linalg.inv() computes the matrix inverse
  • A @ A_inv should be close to identity matrix
  • Singular matrices don't have inverses