Documentation

## 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

`$\begin{array}{l}{a}_{11}{x}_{1}+{a}_{12}{x}_{2}+\dots +{a}_{1n}{x}_{n}={b}_{1}\\ {a}_{21}{x}_{1}+{a}_{22}{x}_{2}+\dots +{a}_{2n}{x}_{n}={b}_{2}\\ \cdots \\ {a}_{m1}{x}_{1}+{a}_{m2}{x}_{2}+\dots +{a}_{mn}{x}_{n}={b}_{m}\end{array}$`

can be represented as the matrix equation $A\cdot \stackrel{\to }{x}=\stackrel{\to }{b}$, where A is the coefficient matrix,

`$A=\left(\begin{array}{ccc}{a}_{11}& \dots & {a}_{1n}\\ ⋮& \ddots & ⋮\\ {a}_{m1}& \cdots & {a}_{mn}\end{array}\right)$`

and $\stackrel{\to }{b}$ is the vector containing the right sides of equations,

`$\stackrel{\to }{b}=\left(\begin{array}{c}{b}_{1}\\ ⋮\\ {b}_{m}\end{array}\right)$`

If you do not have the system of linear equations in the form ```AX = B```, use `equationsToMatrix` to convert the equations into this form. Consider the following system.

`$\begin{array}{l}2x+y+z=2\\ -x+y-z=3\\ x+2y+3z=-10\end{array}$`

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; ```

Use `equationsToMatrix` to convert the equations into the form `AX = B`. The second input to `equationsToMatrix` specifies 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```

Use `linsolve` to solve `AX = B` for the vector of unknowns `X`.

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

From `X`, x = 3, y = 1 and z = -5.

### Solve System of Linear Equations Using solve

Use `solve` instead of `linsolve` if you have the equations in the form of expressions and not a matrix of coefficients. Consider the same system of linear equations.

`$\begin{array}{l}2x+y+z=2\\ -x+y-z=3\\ x+2y+3z=-10\end{array}$`

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 using `solve`. The inputs to `solve` are 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```

`solve` returns the solutions in a structure array. To access the solutions, index into the array.

## Related Topics

#### Mathematical Modeling with Symbolic Math Toolbox

Get examples and videos