## Visualization and diagonalization of quadratic forms¶

In [14]:
import matplotlib.pyplot as plt
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
from numpy import *

# a function to make a contour plot of the quadratic form with matrix A
def qfplot(A,cmap='jet'):
npts = 100
x = linspace(-1,1,npts)
X,Y = meshgrid(x,x)
XY = vstack([X.ravel(),Y.ravel()])
AXY = dot(A,XY)
Z = (XY*AXY).sum(axis=0).reshape(npts,npts)
plt.contourf(X,Y,Z,cmap=cmap)
plt.colorbar()

In [15]:
A = array([[1,-4],[-4,-5]])
print(A)
qfplot(A)

[[ 1 -4]
[-4 -5]]

In [16]:
P = array([[2.,1],[-1,2]])
P /= linalg.norm(P,axis=0)
print(P)
D = dot(P.T,dot(A,P))
print(D.round())
plt.figure(figsize=[15,5])
plt.subplot(1,2,1,aspect=1); plt.title('original')
qfplot(A)
plt.subplot(1,2,2,aspect=1); plt.title('diagonalized')
qfplot(D)

[[ 0.89442719  0.4472136 ]
[-0.4472136   0.89442719]]
[[ 3.  0.]
[-0. -7.]]

In [17]:
A = array([[5,-2],[-2,5]])
print(A)
qfplot(A)

[[ 5 -2]
[-2  5]]

In [18]:
P = array([[1.,-1],[1,1]])
P /= linalg.norm(P,axis=0)
print(P)
D = dot(P.T,dot(A,P))
print(D.round())
plt.figure(figsize=[15,5])
plt.subplot(1,2,1,aspect=1)
qfplot(A)
plt.subplot(1,2,2,aspect=1)
qfplot(D)

[[ 0.70710678 -0.70710678]
[ 0.70710678  0.70710678]]
[[ 3. -0.]
[-0.  7.]]