The goal of this notebook is to provide you with a simple and minimal set of examples, so you can start using the numpy
library and the matplotlib
library to tackle some Linear Algebra and Matrix Analysis problems.
We strongly suggest you to read the numpy quick start tutorial
The following line allows to show plots inside the Jupyter notebook
%matplotlib inline
Import the requiered libraries
numpy
to create and manipulate vectors and matrices, with the name np
matplotlib.pyplot
to plot the results with the name plt
import numpy as np
import matplotlib.pyplot as plt
The main object of NumPy is the np.array
, an homogeneous multidimensional array.
An array is simply is table of elements having the same type.
The elements of an array are indexed using positive integers.
It is possible to convert a python list (or a list of lists ...) into a np.array
, using the np.array
or the np.asarray
functions.
In our case vectors and matrices will be represented as np.array
instances
# encoding a matrix
M = np.asarray([[1,2,3],
[4,5,6]])
# encoding a vector
v = np.asarray([10.,11.,12.])
M
v
The size of a matrix (or vector) represented as a np.array
can be seen using through the ndarray.shape
attribute, and the type of the elements inside the array can be seen using through the ndarray.dtype
attribute
In this example:
int64
)float64
)print(M.shape, v.shape)
print(M.dtype, v.dtype)
np.array
using a python list.np.zeros
) or ones (using np.ones
), specifying the size of the array.np.linspace
(similarly to the range
function)M0 = np.zeros( (3,4) )
print(M0)
M1 = np.ones( (2,3) )
print(M1)
start = 0
stop = 10
size_of_vector = 30
v_arange = np.linspace(start, stop, size_of_vector)
print(v_arange)
It is also possible to use the np.arange
function providing the start, stop and step instead
(but using the linspace you have a better control regarding the final size of the array)
start = 0
stop = 10
step = 0.5
v_arange = np.arange(start, stop, step)
print(v_arange)
It is possible to create arrays filled with random values.
Hereafter we only give some examples, but you can check the numpy.random documentation for more functions
Mg = np.random.randn(2,3)
print(Mg)
Mu = np.random.random((2,3))
print(Mu)
Arithmetic operators are applied elementwise on arrays: the result is output in a new array
Mu_x10 = Mu * 10
print(Mu_x10)
Mg_p10 = Mg + 10
print(Mg_p10)
Mu_x_Mg = Mu * Mg
print(Mu_x_Mg)
Mu_square = Mu**2
print(Mu_square)
Numpy can also to apply basic operations between a matrix and a vector, row by row, such as in this example:
v = np.asarray([-10,1000,-1000])
print(Mu)
print(Mu * v)
It is possible to apply conditions to arrays to get boolean arrays.
Here we check elementwise if the values of $M_u$ are greater than 0.5, and we get a boolean matrix (true if the element is greater than 0.5 and false otherwise)
Mu_g05 = Mu>0.5
print(Mu)
print(Mu_g05)
Here we check elementwise if the values of $M_g$ are greater than 0, and we get a boolean matrix (true if the element is greater than 0 and false otherwise)
Mg_g0 = Mg>0
print(Mg)
print(Mg_g0)
It is also possible to apply boolean operations, for instance:
np.logical_and
will apply the "and" logical operator to two arrays elementwisenp.logical_or
will apply the "or" logical operator to two arrays elementwiseHereafter we apply the and operator to the results of the two previous steps
Mu_g05_AND_Mg_g0 = np.logical_and(Mu_g05, Mg_g0)
print(Mu_g05_AND_Mg_g0)
numpy
provides many universal functions such as :
np.exp
and np.log
(exponential and logarithm)np.sin
and np.cos
(sine and cosine)np.sqrt
(square root)np.abs
(absolute value)np.max
and np.min
(maximum and minimum)np.sum
(sum)np.mean
and np.std
(mean and standard deviation)This functions can also be applied elementwise to an array
compute the exponential of each element of $M_u$
exp_Mu = np.exp(Mu)
print(exp_Mu)
Some functions, that aggregate many elements can be applied to each row or each column of a matrix.
Hereafter we sum the elements of the matrix $M_u$ along each row and then along each column
# tell axis = 1 to apply the function to each row
# Mu has two rows
Mu.sum(axis=1)
# tell axis = 0 to apply the function to each column
# Mu has three columns
Mu.sum(axis=0)
Get the element in row 0 and column 1 from $M_u$
Mu[0,1]
Get all the elements of row 0 of $M_u$
Mu[0,:]
Get all the elements of column 2 of $M_u$
Mu[:,2]
Get all the rows for the first 2 columns of $M_u$
Mu[:,:2]
# or
Mu[:,[0,1]]
It is also possible to get elements applying a boolean mask. In this case we will get the elements for which the correspoing element in the boolean mask is true
For instance we will get the elements from $M_u$ s.t. $M_u > 0.5$, using the matrixes previously generated
print(Mu_g05)
print(Mu)
print(Mu[Mu_g05])
It is possible to apply basic linear algebra operations with arrays:
Moreover the numpy.linalg
package has many linear algebra algorithms ready to use
2 ways to compute $M_u^*$ the transpose of $M_u$
print(Mu)
print(Mu.T)
print(Mu.transpose())
Compute $M_u^* \cdot M_g$
$M_u$ is $2\times 3$, so $M_u^*$ is $3 \times 2$, and $M_g$ is $2 \times 3$, so the resulting matrix is $3 \times 3$
Mu_t_Mg = (Mu.T).dot(Mg)
print(Mu_t_Mg)
Compute the inverse of $M_u^* \cdot M_g$
np.linalg.inv(Mu_t_Mg)
Get a $4\times 4$ identity matrix
I = np.eye(4)
print(I)
It is possible to plot matrices using the plt.imshow
function
Beware, this function cannot plot a vector !!!
plt.imshow(Mu)
In order to plot vectors you can use the plt.plot
function
x = np.linspace(3,13,10)
y = np.random.randn(10)
# plot y as a function of x
plt.plot(x,y,"o-",color="red")
# plot y as a function of the index of its elements
plt.plot(y,"--",color="blue")
# Change the label of the x and y axis
plt.xlabel("X", fontsize=10)
plt.ylabel("Y", fontsize=10)
It is also possible to stack different arrays, to split an array in small arrays, to reshape arrays ... but we are not going to see these features here