lettura simple

How to solve a system of equations in Octave

In this lesson I explain how to solve a system of linear equations in Octave using matrix and vector calculus.

I'll give you a practical example.

This system of equations consists of two linear equations with two variables

$$ \begin{cases} x+5y-3 = 0 \\ \\ 2x-4y+8=0 \end{cases} $$

Write the system in the general form ax+by=c

$$ \begin{cases} x+5y=3 \\ \\ 2x-4y=-8 \end{cases} $$

Then transform the system of equations into a vector equation

$$ \begin{pmatrix} 1 & 5 \\ 2 & -4 \end{pmatrix} \cdot \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} 3 \\ -8 \end{pmatrix} $$

The first matrix is the matrix of the coefficients of the variables x and y.

$$ A = \begin{pmatrix} 1 & 5 \\ 2 & -4 \end{pmatrix} $$

Type A=[1,5; 2,-4] to declare the matrix of the coefficients in Octave.

>> A = [ 1 , 5 ; 2 , -4 ]
A =
1 5
2 --4

The first column vector is the vector of variables.

They are the values of the variables that you need to find

$$ \vec{x} = \begin{pmatrix} x \\ y \end{pmatrix} $$

The second column vector is the vector of the numerical terms.

$$ \vec{b} = \begin{pmatrix} 3 \\ -8 \end{pmatrix} $$

Type b=[3; -8] to declare the column vector of the numerical terms.

>> b = [ 3 ; -8 ]
b =
3
-8

In vector form, the system of equations is the product of a matrix and a vector.

$$ A \cdot \vec{x} = \vec{b} $$

To find solutions to the system of equations, determine the vector x as a function of everything else.

$$ \vec{x} = A^{-1} \cdot \vec{b} $$

Where A-1 is the inverse matrix of the coefficient matrix A.

Now, calculate the expression A-1·b in Octave

>> inv(A)*b
ans =
-2
1

The result is the x and y values of the vector of variables.

$$ \vec{x} = \begin{pmatrix} x \\ y \end{pmatrix} = \begin{pmatrix} -2 \\ 1 \end{pmatrix} $$

You have found the solution to the system of equations

$$ x=-2 $$

$$ y=1 $$

The system of equations has a solution (x;y)=(-2;1)

Check if the solution is correct. Use the values x=-2 and y=1 in the system of equations $$ \begin{cases} x+5y=3 \\ \\ 2x-4y=-8 \end{cases} $$ $$ \begin{cases} -2 + 5 \cdot 1 =3 \\ \\ 2 \cdot (-2) -4 \cdot 1 =-8 \end{cases} $$ $$ \begin{cases} 3 =3 \\ \\ -8 =-8 \end{cases} $$ Both equations of the system are satisfied. So the solution x=-2 and y=1 is correct.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin