# Exercise 10.1: Least squares

Generate matrix $A\in {R}^{m\ast n}$$A∈R^{m*n}$ with $m>n$$m > n$. Also generate some vector $b\in {R}^{m}$$b∈ R^m$.
Now find $x=\mathrm{arg}\underset{x}{min}||Ax-b|{|}_{2}$$x = \arg \min_x||Ax - b||_2$.
Print the norm of the residual.

import numpy as np
from scipy import linalg

m, n = 5, 4
A = np.mat(np.random.rand(m, n))
b = np.mat(np.random.rand(m, 1))

x, res, rnk, s = linalg.lstsq(A, b)

norm = linalg.norm(A.dot(x) - b, ord = 2)

print("A =\n",A)
print("b =\n",b)
print("Solution =\n", x)
print("Norm =", res / n)

# Exercise 10.2: Optimization

Find the maximum of the function $f\left(x\right)=si{n}^{2}\left(x-2\right){e}^{-{x}^{2}}$$f(x) = sin^2(x-2){e^{-x^2}}$.

import numpy as np
from scipy import optimize
from matplotlib import pyplot as plt

def func(x):
return -np.sin(x - 2) ** 2 * np.exp(-x * x)

maximum = optimize.fmin(func, 0)
print(maximum)

# Exercise 10.3: Pairwise distances

Let $X$$X$ be a matrix with $n$$n$ rows and $m$$m$ columns. How can you compute the pairwise distances between every two rows?
As an example application, consider $n$$n$ cities, and we are given their coordinates in two columns. Now we want a nice table that tells us for each two cities, how far they are apart.
Again, make sure you make use of Scipy’s functionality instead of writing your own routine.

import numpy as np
from scipy.spatial import distance

m, n = 5, 2
x = np.random.rand(m, n)
print("X =\n", x)
y = distance.pdist(x)
z = distance.squareform(y)
print("Distance =\n", z)