Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Implementing Matrix Transformation in Python | Linear Algebra Foundations
Mathematics for Data Science

bookImplementing Matrix Transformation in Python

Matrices allow us to model, manipulate, and visualize linear systems and geometric transformations.

Step 1: Solving a Linear System

We define a system of equations:

2x+y=5xy=12x + y = 5 \\ x - y = 1

This is rewritten as:

123456789
import numpy as np A = np.array([[2, 1], # Coefficient matrix [1, -1]]) b = np.array([5, 1]) # Constants (RHS) x_solution = np.linalg.solve(A, b) print(x_solution)
copy

This finds the values of xx and yy that satisfy both equations.

Why this matters: solving systems of equations is foundational in data science — from fitting linear models to solving optimization constraints.

Step 2: Applying Linear Transformations

We define a vector:

v = np.array([[2], [3]])

Then apply two transformations:

Scaling

We stretch xx by 2 and compress yy by 0.5:

S = np.array([[2, 0],
              [0, 0.5]])

scaled_v = S @ v

This performs:

Sv=[2000.5][23]=[41.5]S \cdot v = \begin{bmatrix} 2 & 0 \\ 0 & 0.5 \end{bmatrix} \begin{bmatrix} 2 \\ 3 \end{bmatrix} = \begin{bmatrix} 4 \\ 1.5 \end{bmatrix}

Rotation

We rotate the vector 90°90° counterclockwise using the rotation matrix:

theta = np.pi / 2
R = np.array([[np.cos(theta), -np.sin(theta)],
              [np.sin(theta),  np.cos(theta)]])

rotated_v = R @ v

This yields:

Rv=[0110][23]=[32]R \cdot v = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 2 \\ 3 \end{bmatrix} = \begin{bmatrix} -3 \\ 2 \end{bmatrix}

Step 3: Visualizing the Transformations

Using matplotlib, we plot each vector from the origin, with their coordinates labeled:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
import matplotlib.pyplot as plt # Define original vector v = np.array([[2], [3]]) # Scaling S = np.array([[2, 0], [0, 0.5]]) scaled_v = S @ v # Rotation theta = np.pi / 2 R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) rotated_v = R @ v # Vizualization origin = np.zeros(2) fig, ax = plt.subplots(figsize=(6, 6)) # Plot original ax.quiver(*origin, v[0], v[1], angles='xy', scale_units='xy', scale=1, color='blue', label='Original') # Plot scaled ax.quiver(*origin, scaled_v[0], scaled_v[1], angles='xy', scale_units='xy', scale=1, color='green', label='Scaled') # Plot rotated ax.quiver(*origin, rotated_v[0], rotated_v[1], angles='xy', scale_units='xy', scale=1, color='red', label='Rotated') # Label vector tips ax.text(v[0][0]+0.2, v[1][0]+0.2, "(2, 3)", color='blue') ax.text(scaled_v[0][0]+0.2, scaled_v[1][0]+0.2, "(4, 1.5)", color='green') ax.text(rotated_v[0][0]-0.6, rotated_v[1][0]+0.2, "(-3, 2)", color='red') # Draw coordinate axes ax.annotate("", xy=(5, 0), xytext=(0, 0), arrowprops=dict(arrowstyle="->", linewidth=1.5)) ax.annotate("", xy=(0, 5), xytext=(0, 0), arrowprops=dict(arrowstyle="->", linewidth=1.5)) ax.text(5.2, 0, "X", fontsize=12) ax.text(0, 5.2, "Y", fontsize=12) ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) ax.set_aspect('equal') ax.grid(True) ax.legend() plt.show()
copy

Why this matters: data science workflows often include transformations — for example:

  • Principal Component Analysis (rotates data);
  • Feature normalization (scales axes;
  • Dimensionality reduction (projections.

By visualizing vectors and their transformations, we see how matrices literally move and reshape data in space.

1. What does this line define in the code?

2. What is the output of this operation?

3. What is the purpose of this rotation matrix?

question mark

What does this line define in the code?

Select the correct answer

question mark

What is the output of this operation?

Select the correct answer

question mark

What is the purpose of this rotation matrix?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

Can you explain how the matrix equation relates to the original system of equations?

How does the scaling and rotation affect the original vector?

Can you walk me through the visualization code step by step?

Awesome!

Completion rate improved to 1.89

bookImplementing Matrix Transformation in Python

Scorri per mostrare il menu

Matrices allow us to model, manipulate, and visualize linear systems and geometric transformations.

Step 1: Solving a Linear System

We define a system of equations:

2x+y=5xy=12x + y = 5 \\ x - y = 1

This is rewritten as:

123456789
import numpy as np A = np.array([[2, 1], # Coefficient matrix [1, -1]]) b = np.array([5, 1]) # Constants (RHS) x_solution = np.linalg.solve(A, b) print(x_solution)
copy

This finds the values of xx and yy that satisfy both equations.

Why this matters: solving systems of equations is foundational in data science — from fitting linear models to solving optimization constraints.

Step 2: Applying Linear Transformations

We define a vector:

v = np.array([[2], [3]])

Then apply two transformations:

Scaling

We stretch xx by 2 and compress yy by 0.5:

S = np.array([[2, 0],
              [0, 0.5]])

scaled_v = S @ v

This performs:

Sv=[2000.5][23]=[41.5]S \cdot v = \begin{bmatrix} 2 & 0 \\ 0 & 0.5 \end{bmatrix} \begin{bmatrix} 2 \\ 3 \end{bmatrix} = \begin{bmatrix} 4 \\ 1.5 \end{bmatrix}

Rotation

We rotate the vector 90°90° counterclockwise using the rotation matrix:

theta = np.pi / 2
R = np.array([[np.cos(theta), -np.sin(theta)],
              [np.sin(theta),  np.cos(theta)]])

rotated_v = R @ v

This yields:

Rv=[0110][23]=[32]R \cdot v = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 2 \\ 3 \end{bmatrix} = \begin{bmatrix} -3 \\ 2 \end{bmatrix}

Step 3: Visualizing the Transformations

Using matplotlib, we plot each vector from the origin, with their coordinates labeled:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
import matplotlib.pyplot as plt # Define original vector v = np.array([[2], [3]]) # Scaling S = np.array([[2, 0], [0, 0.5]]) scaled_v = S @ v # Rotation theta = np.pi / 2 R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) rotated_v = R @ v # Vizualization origin = np.zeros(2) fig, ax = plt.subplots(figsize=(6, 6)) # Plot original ax.quiver(*origin, v[0], v[1], angles='xy', scale_units='xy', scale=1, color='blue', label='Original') # Plot scaled ax.quiver(*origin, scaled_v[0], scaled_v[1], angles='xy', scale_units='xy', scale=1, color='green', label='Scaled') # Plot rotated ax.quiver(*origin, rotated_v[0], rotated_v[1], angles='xy', scale_units='xy', scale=1, color='red', label='Rotated') # Label vector tips ax.text(v[0][0]+0.2, v[1][0]+0.2, "(2, 3)", color='blue') ax.text(scaled_v[0][0]+0.2, scaled_v[1][0]+0.2, "(4, 1.5)", color='green') ax.text(rotated_v[0][0]-0.6, rotated_v[1][0]+0.2, "(-3, 2)", color='red') # Draw coordinate axes ax.annotate("", xy=(5, 0), xytext=(0, 0), arrowprops=dict(arrowstyle="->", linewidth=1.5)) ax.annotate("", xy=(0, 5), xytext=(0, 0), arrowprops=dict(arrowstyle="->", linewidth=1.5)) ax.text(5.2, 0, "X", fontsize=12) ax.text(0, 5.2, "Y", fontsize=12) ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) ax.set_aspect('equal') ax.grid(True) ax.legend() plt.show()
copy

Why this matters: data science workflows often include transformations — for example:

  • Principal Component Analysis (rotates data);
  • Feature normalization (scales axes;
  • Dimensionality reduction (projections.

By visualizing vectors and their transformations, we see how matrices literally move and reshape data in space.

1. What does this line define in the code?

2. What is the output of this operation?

3. What is the purpose of this rotation matrix?

question mark

What does this line define in the code?

Select the correct answer

question mark

What is the output of this operation?

Select the correct answer

question mark

What is the purpose of this rotation matrix?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 6
some-alt