Section 4.7 Solving System of Equations
We already saw how MATLAB can be used to solve a system of equation by using the matrix inverse. Just to review:
Given a system of linear equations, for example
8x + 5y + 3z = 0
1x + 2y + 5z = 1
2x + 9y + 4z = 3
we put the system into matrix form:
A * x = b
Here, A is the matrix of coefficients and b is the right-hand side. If the matrix A has an inverse that we can solve for our unknown x via \(x = A^{-1} b \text{.}\) In MATLAB:
>> A = [8 5 3; 1 2 5; 2 9 4]; % 3x3 matrix
>> b = [0; 1; 3]; % 3x1 RHS
>> x = A^-1 * b
x =
-0.2550
0.3386
0.1155
This technique is actually not very good, especially for large matrices as it becomes slow and inaccurate. It is much better to solve systems of equations using Gaussian Elimination:
\begin{equation*}
A x = b
\end{equation*}
By hand, you manipulate the rows of this equation in a well-defined way (adding multiples of one equation to another) so as to arrive at a system that has only I*x on the left-hand side and the solution on the right.
To do so in MATLAB, we use the left division operator (I told you it would make sense eventually!):
>> A = [8 5 3; 1 2 5; 2 9 4]; % 3x3 matrix
>> b = [0; 1; 3]; % 3x1 RHS
>> x = A \ b % Gaussian Elimination!
x =
-0.2550
0.3386
0.1155
The left division operator is short-hand for solving the system using the numerical technique that we know as Gaussian elimination. It is much better to use for large systems, as it is faster and more accurate!
How much better?
On my computer, a system of 1000 equations and unknowns takes the following time to compute:
>> xi = A^-1 * b; %4.1049 seconds
>> xg = A \ b; %0.6152 seconds
>> max(abs(xg-xi)) %difference is numerical round-off
ans =
1.3581e-13
So more than 6.6 times faster!
Activity 4.8.
Solve the following system of three linear equations:
\begin{equation*}
3x - 2y + 5z = 7.5
\end{equation*}
\begin{equation*}
-4.5x + 2y + 3z = 5.5
\end{equation*}
\begin{equation*}
5x + y - 2.5z = 4.5
\end{equation*}
Please paste your MATLAB code in the answer box.
Activity 4.9.
Try to understand the built-in function clock. What does it return? Use this function to find today’s date (store it in a variable today - i.e. an array of three integers in the order year, month, day). Furthermore, find the current time and store them in a variable time (an array of three integers: hour, minutes, seconds).