This section explains how to solve systems of equations using Symbolic Math Toolbox™ software. As an example, suppose you have the system
and you want to solve for x and y. First, create the necessary symbolic objects.
syms x y alpha
There are several ways to address the output of solve. One is to use a two-output call
[sol_x,sol_y] = solve(x^2*y^2 == 0, x-y/2 == alpha)
sol_x = alpha 0 sol_y = 0 -2*alpha
Modify the first equation to x2y2 = 1. The new system has more solutions.
[sol_x,sol_y] = solve(x^2*y^2 == 1, x-y/2 == alpha)
produces four distinct solutions:
sol_x = alpha/2 + (alpha^2 + 2)^(1/2)/2 alpha/2 + (alpha^2 - 2)^(1/2)/2 alpha/2 - (alpha^2 + 2)^(1/2)/2 alpha/2 - (alpha^2 - 2)^(1/2)/2 sol_y = (alpha^2 + 2)^(1/2) - alpha (alpha^2 - 2)^(1/2) - alpha - alpha - (alpha^2 + 2)^(1/2) - alpha - (alpha^2 - 2)^(1/2)
Since you did not specify the dependent variables, solve uses symvar to determine the variables.
This way of assigning output from solve is quite successful for "small" systems. Plainly, if you had, say, a 10-by-10 system of equations, typing
[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10] = solve(...)
is both awkward and time consuming. To circumvent this difficulty, solve can return a structure whose fields are the solutions. For example, solve the system of equations u^2 - v^2 = a^2, u + v = 1, a^2 - 2*a = 3:
syms u v a S = solve(u^2 - v^2 == a^2, u + v == 1, a^2 - 2*a == 3)
The solver returns its results enclosed in this structure:
S = a: [2x1 sym] u: [2x1 sym] v: [2x1 sym]
The solutions for a reside in the "a-field" of S. That is,
ans = -1 3
Similar comments apply to the solutions for u and v. The structure S can now be manipulated by field and index to access a particular portion of the solution. For example, if you want to examine the second solution, you can use the following statement
s2 = [S.a(2), S.u(2), S.v(2)]
to extract the second component of each field.
s2 = [ 3, 5, -4]
The following statement
M = [S.a, S.u, S.v]
creates the solution matrix M
M = [ -1, 1, 0] [ 3, 5, -4]
whose rows comprise the distinct solutions of the system.
Linear systems of equations can also be solved using matrix division. For example, solve this system:
clear u v x y syms u v x y S = solve(x + 2*y == u, 4*x + 5*y == v); sol = [S.x; S.y] A = [1 2; 4 5]; b = [u; v]; z = A\b
sol = (2*v)/3 - (5*u)/3 (4*u)/3 - v/3 z = (2*v)/3 - (5*u)/3 (4*u)/3 - v/3
Thus sol and z produce the same solution, although the results are assigned to different variables.