Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Multiply a matrix with an array of vectors

Tags:

numpy

scipy

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)
like image 720
Basti Avatar asked Nov 24 '14 13:11

Basti


People also ask

How do you perform matrix multiplication on the NumPy arrays?

To multiply two matrices use the dot() function of NumPy. It takes only 2 arguments and returns the product of two matrices.

How do you perform matrix multiplication on the NumPy arrays A and B?

NumPy Multiplication Matrix If both a and b are 2-D (two dimensional) arrays -- Matrix multiplication. If either a or b is 0-D (also known as a scalar) -- Multiply by using numpy. multiply(a, b) or a * b. If a is an N-D array and b is a 1-D array -- Sum product over the last axis of a and b.


1 Answers

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)
like image 79
Ondro Avatar answered Sep 25 '22 22:09

Ondro