Find a Guide

Solving Linear Systems using Matrices in MATLAB

Solving a System

I would be remise if I did not mention how we could solve matrices in MATLAB; after all, the "MAT" in MATLAB stands for matrix!

Let's start by defining a system of equations.

$$ 3x + y - 7z = 12 $$ $$ x - y +2z = -4 $$ $$ 2x - 3y + 4z = 6 $$
Their coefficients can then be taken and put into a system of equation as so:

$$ \begin{bmatrix} 3 & 1 & -7 \\ 1 & -1 & 2 \\ 2 & -3 & 4 \end{bmatrix} \begin{Bmatrix} x \\ y \\ z \end{Bmatrix} = \begin{Bmatrix} 12 \\ -4 \\ 6 \end{Bmatrix} $$ After the system has been set up, we can enter the matrices in MATLAB. Let's follow the format $ Ax = b $ and enter $ A $ and $ b $ into MATLAB.

matlab

A = [ 3  1 -7
         1 -1  2
         2 -3  4 ];

b = [12; -4; 6];

Now that $ A $ and $ b $ have been defined, we can solve for the vector x.

In mathematics, solving for x would include taking the inverse of A on both sides to isolate x, like this: $ x = A^{-1} b $. In MATLAB, we can denote this inverse as ' \ ', or a backslash. Let's try it.

matlab

% from before
A = [ 3  1 -7
         1 -1  2
         2 -3  4 ];

b = [12; -4; 6];

x = A\b
% output: -5.6923
%              -14.0000
%              -6.1538

Now we can use MATLAB to solve systems of equations for us!

Find a Guide