Last active
April 18, 2024 13:22
-
-
Save snowch/ea767bc05209104b312304c6c63ce642 to your computer and use it in GitHub Desktop.
Example vector subspace for the book "Practical Linear Algebra for Data Science"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
from mpl_toolkits.mplot3d import Axes3D | |
# Define the vectors | |
v1 = np.array([1, 0, 2]) | |
v2 = np.array([-1, 2, 3]) | |
# Create a grid of values for t1 and t2 | |
t1, t2 = np.mgrid[-1:1:0.1, -1:1:0.1] | |
# Ensure t1 and t2 have compatible shapes for broadcasting | |
t1 = t1.flatten() | |
t2 = t2.flatten() | |
# Create points in the subspace by taking linear combinations of v1 and v2 | |
points = t1[:, np.newaxis] * v1 + t2[:, np.newaxis] * v2 | |
# Extract x, y, and z coordinates | |
x, y, z = points[:, 0], points[:, 1], points[:, 2] | |
# Create the 3D plot | |
fig = plt.figure() | |
ax = fig.add_subplot(111, projection='3d') | |
ax.scatter(x, y, z, s=2) | |
# Add arrows for the vectors | |
ax.quiver(0, 0, 0, v1[0], v1[1], v1[2], color='r', label='v1', arrow_length_ratio=0.3) | |
ax.quiver(0, 0, 0, v2[0], v2[1], v2[2], color='g', label='v2', arrow_length_ratio=0.3) | |
# Set labels and title | |
ax.set_xlabel('X') | |
ax.set_ylabel('Y') | |
ax.set_zlabel('Z') | |
ax.set_title('Subspace of Vectors [1, 0, 2] and [-1, 2, 3]') | |
plt.legend() # Show the legend | |
# Display the plot | |
plt.show() |
Author
snowch
commented
Apr 18, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment