I'm having a hard time getting into numpy. What I want in the end is a simple quiver plot of vectors that have been transformed by a matrix. I've read many times to just use arrays for matrices, fair enough. And I've got a meshgrid for x and y coordinates
X,Y = np.meshgrid( np.arange(0,10,2),np.arange(0,10,1) )
a = np.array([[1,0],[0,1.1]])
But even after googling and trying for over two hours, I can't get the resulting vectors from the matrix multiplication of a
and each of those vectors. I know that quiver takes the component length as input, so the resulting vectors that go into the quiver function should be something like np.dot(a, [X[i,j], Y[i,j]]) - X[i,j]
for the x-component, where i and j iterate over the ranges.
I can of course program that in a loop, but numpy has sooo many builtin tools to make these vectorized things handy that I'm sure there's a better way.
edit: Alright, here's the loop version.
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(10,10))
n=10
X,Y = np.meshgrid( np.arange(-5,5),np.arange(-5,5) )
print("val test", X[5,3])
a = np.array([[0.5,0],[0,1.3]])
U = np.zeros((n,n))
V = np.zeros((n,n))
for i in range(10):
for j in range(10):
product = np.dot(a, [X[i,j], Y[i,j]]) #matrix with vector
U[i,j] = product[0]-X[i,j] # have to substract the position since quiver accepts magnitudes
V[i,j] = product[1]-Y[i,j]
Q = plt.quiver( X,Y, U, V)
You can either do matrix multiplication "manually" using NumPy broadcasting like this:
import numpy as np
import matplotlib.pyplot as plt
X,Y = np.meshgrid(np.arange(-5,5), np.arange(-5,5))
a = np.array([[0.5, 0], [0, 1.3]])
U = (a[0,0] - 1)*X + a[0,1]*Y
V = a[1,0]*X + (a[1,1] - 1)*Y
Q = plt.quiver(X, Y, U, V)
or if you want to use np.dot
you have to flatten your X
and Y
arrays and combine them to appropriate shape as follows:
import numpy as np
import matplotlib.pyplot as plt
X,Y = np.meshgrid(np.arange(-5,5), np.arange(-5,5))
a = np.array([[0.5, 0], [0, 1.3]])
U,V = np.dot(a-np.eye(2), [X.ravel(), Y.ravel()])
Q = plt.quiver(X, Y, U, V)