System of Linear Equation in MATLAB
-
Solve the System of Linear Equations Using the
solve()
Function in MATLAB -
Solve the System of Linear Equations Using the
linsolve()
Function in MATLAB
This tutorial will discuss solving the system of linear equations using the solve()
and linsolve()
functions in Matlab.
Solve the System of Linear Equations Using the solve()
Function in MATLAB
We can use the Matlab built-in function solve()
to solve the system of linear equations in Matlab. First of all, we can define the variables using the syms
variable. After that, we can write the equations in Matlab. After that, we need to use the function solve()
to solve the equations. For example, let’s define some equations in Matlab and find their solution using the solve()
function. See the code below.
syms x y z
eq1 = 2*x + y + 2*z == 1;
eq2 = 2*x + 5*y - z == 2;
eq3 = -3*x + 2*y + 6*z == 10;
matx = solve([eq1, eq2, eq3], [x, y, z]);
xValue = matx.x
yVlaue = matx.y
zValue = matx.z
Output:
xValue =
-82/93
yVlaue =
29/31
zValue =
85/93
As you can see, there are three variables in the equation, and there are three answers. You can also use vapsolve()
function instead of the solve()
function to get the answer in numeric. To use the vpasolve()
function, you need to change the function name solve
to vpasolve
in the above code. If the equations are in matrix form, you can use the linsolve()
function.
Solve the System of Linear Equations Using the linsolve()
Function in MATLAB
The function linsolve()
is used instead of the solve()
function if you have matrices instead of equations. We can also convert the equations to matrix form using the equationsToMatrix()
function. For example, let’s define some equations in Matlab and find their solution using the linsolve()
function. See the code below.
syms x y z
eq1 = 2*x + y + 2*z == 1;
eq2 = 2*x + 5*y - z == 2;
eq3 = -3*x + 2*y + 6*z == 10;
[matA,matB] = equationsToMatrix([eq1, eq2, eq3], [x, y, z])
matX = linsolve(matA,matB)
Output:
matA =
[ 2, 1, 2]
[ 2, 5, -1]
[ -3, 2, 6]
matB =
1
2
10
matX =
-82/93
29/31
85/93
The solve()
and linsolve()
functions come with the symbolic math Toolbox, so make sure you have installed the toolbox to use these functions.