In [1]:
# this line is needed for the web notebook only
%matplotlib inline
CIVL4250 Numerical Methods in Engineering
Dr Dorival Pedroso
The code for this notebook is available in https://github.com/cpmech/CIVL4250py
In [2]:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0, 1.0, 11)
print x
Using Matplotlib [1] (aka PyPlot) for plotting and Numpy [2] for numerical computations.
In [13]:
x = np.linspace(0.0, 2.0*np.pi, 101)
y = np.sin(x)
plt.plot(x, y, 'b-', lw=3, color='#ff9933')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Vectors and matrices are created with the array structure from NumPy that takes one list as argument.
To create a matrix, array takes one list of lists.
The matrix multiplication is computed with the dot function from Numpy.
In [7]:
u = np.array([1.0, 2.0, 3.0]) # vector
M = np.array([[1.0, -1.0, 1.0],
[-2.0, 2.0, 2.0],
[-3.0, 3.0, 3.0]]) # matrix
v = np.dot(M, u) # matrix product: v = M times u
print v
To solve a linear system, the solve function from linalg can be used.
For example, given the following linear system of equations:
$$ \begin{bmatrix} 2 & \phantom{-}3 & 0 & 0 & 0 & \\ 3 & \phantom{-}0 & 4 & 0 & 6 & \\ 0 & -1 & -3 & 2 & 0 & \\ 0 & \phantom{-}0 & 1 & 0 & 0 & \\ 0 & \phantom{-}4 & 2 & 0 & 1 & \end{bmatrix} \begin{Bmatrix} x_0 \\ x_1 \\ x_2 \\ x_3 \\ x_4 \end{Bmatrix} = \begin{Bmatrix} 8 \\ 45 \\ -3 \\ 3 \\ 19 \end{Bmatrix} $$The components $x_i$ can be found as follows
In [12]:
A = np.array([[2, 3, 0, 0, 0],
[3, 0, 4, 0, 6],
[0, -1, -3, 2, 0],
[0, 0, 1, 0, 0],
[0, 4, 2, 0, 1]])
b = np.array([8, 45, -3, 3, 19])
x = np.linalg.solve(A, b)
print x