The whole preceding process is implemented in code as follows:
- Import relevant classes within a package:
from scipy import linalg
- Initialize the right-hand side and left-hand side matrices (input and output matrices):
A=[[1,3,5],[2,5,1],[2,3,8]]
b=[[10],[8],[3]]
Now, we will look into the function used to solve the equation A*x = b.
Method 1 (using the functions we have learnt so far)
Multiply the inverse of A with b.
np.dot(linalg.inv(A),b)
Method 2 (using the solve function)
Using the solve function within the scipy package helps in solving the equation straight away:
scipy.linalg.solve(x, b)
The output of either of the preceding methods is the solution, as follows:
array([[-9.28], [ 5.16], [ 0.76]])
Calculating the determinant of a matrix
As seen earlier, in order to solve a linear system, we need to calculate the inverse of a matrix first, which in turn requires us to calculate the determinant of the matrix.
The way in which the determinant is calculated is as follows:
The determinant of a matrix in Python can be calculated by using the det function in scipy.linalg.
The same preceding calculation can be implemented in code, as follows:
linalg.det(A)