DDC-27: Visualize matrix-vector products
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
Create the following matrix and vector in numpy:
\(\begin{align}
M &= \begin{bmatrix}.5&1\\1&.5\end{bmatrix} \\[1em]
v &= \begin{bmatrix}1\\\alpha\end{bmatrix}
\end{align}\)
Plot v and Mv for 300 linearly spaced values of α between -2 and +2.
.
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
.
.
.
.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
M = np.array([[.5,1],[1,.5]])
for a in np.linspace(-2,2,300):
v = np.array([1,a])
Mv = M@v
plt.plot([0,v[0]],[0,v[1]],color=cm.magma((a+2)/4))
plt.plot([0,Mv[0]],[0,Mv[1]],color=cm.plasma((a+2)/4))
plt.axis('off')
plt.show()


