Main Content

Solve System of Linear Equations

This section shows you how to solve a system of linear equations using the Symbolic Math Toolbox™.

Solve System of Linear Equations Using linsolve

A system of linear equations

a 11 x 1 + a 12 x 2 + + a 1 n x n = b 1 a 21 x 1 + a 22 x 2 + + a 2 n x n = b 2 a m 1 x 1 + a m 2 x 2 + + a m n x n = b m

can be represented as the matrix equation A x = b , whereAis the coefficient matrix,

A = ( a 11 a 1 n a m 1 a m n )

and b is the vector containing the right sides of equations,

b = ( b 1 b m )

If you do not have the system of linear equations in the formAX = B, useequationsToMatrixto convert the equations into this form. Consider the following system.

2 x + y + z = 2 x + y z = 3 x + 2 y + 3 z = 10

Declare the system of equations.

syms x y z eqn1 = 2*x + y + z == 2; eqn2 = -x + y - z == 3; eqn3 = x + 2*y + 3*z == -10;

UseequationsToMatrixto convert the equations into the formAX = B. The second input toequationsToMatrixspecifies the independent variables in the equations.

[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])
A = [ 2, 1, 1] [ -1, 1, -1] [ 1, 2, 3] B = 2 3 -10

Uselinsolveto solveAX = Bfor the vector of unknownsX.

X = linsolve(A,B)
X = 3 1 -5

FromX,x= 3,y= 1andz= -5.

Solve System of Linear Equations Using solve

Usesolveinstead oflinsolveif you have the equations in the form of expressions and not a matrix of coefficients. Consider the same system of linear equations.

2 x + y + z = 2 x + y z = 3 x + 2 y + 3 z = 10

Declare the system of equations.

syms x y z eqn1 = 2*x + y + z == 2; eqn2 = -x + y - z == 3; eqn3 = x + 2*y + 3*z == -10;

Solve the system of equations usingsolve. The inputs tosolveare a vector of equations, and a vector of variables to solve the equations for.

sol = solve([eqn1, eqn2, eqn3], [x, y, z]); xSol = sol.x ySol = sol.y zSol = sol.z
xSol = 3 ySol = 1 zSol = -5

solvereturns the solutions in a structure array. To access the solutions, index into the array.

Related Topics