Systems of linear equations: Solving systems of linear equations in MATLAB
Solving systems via linsove and solve
MATLAB has sufficient built-in facilities to solve systems of linear equations numerically. We illustrate them using the system \[ \left\{\begin{array}{rrrrrl} x & + & 2y & + & 3z & =\;2\\ & & y & + & 2z & =\;1\\ 3x & + & y & + & z & =\;3 \end{array}\right. \] with one solution, namely \[ \cv{x\\y\\z}=
\left(\!\!\begin{array}{r} 1\\-1\\1\end{array}\right)\]
We start with entering the system of equations in a MATLAB session and then determine the appropriate matrix form with the command equationsToMatrix
.
>> syms xyz
>> sys = [x + 2*y + 3*z == 2, y + 2*z == 1, 3*x + y + z == 3];
>> [A,b] = equationsToMatrix(sys)
A =
[ 1, 2, 3]
[ 0, 1, 2]
[ 3, 1, 1]
b =
2
1
3
We can now use linsolve
to find the vector \(\vec{v}\) so that \(A\vec{v}=\vec{b}\)
>> v = linsolve(A,b)
v =
1
-1
1
The solution of the original system stands for \(\vec{v}=\cv{x \\ y \\ z}\) and we would have also found this solution with solve
without going first over to the matrix form.
>> sol = solve(sys, [x, yz]);
>> v = [sol.x, sol.y, sol.z]; v
v =
[ 1, -1, 1]
Advantage of the matrix form is that you can better control the theory for solving equations. For example, you can apply Gaussian elimination to solve the system. The name of the function rref
is an acronym for reduced row echelon form.
>> Ab = [A,b]; Ab % the augmented matrix
Ab =
[ 1, 2, 3, 2]
[ 0, 1, 2, 1]
[ 3, 1, 1, 3]
>> rref(Ab) % computation of the reduced echelon form
ans =
[ 1, 0, 0, 1]
[ 0, 1, 0, -1]
[ 0, 0, 1, 1]
>> ans(:,4) % selection of the fourth column
ans =
1
-1
1
In MATLAB you can also calculate this by 'reverse division':
>> A\b
ans =
1
-1
1