Main Content

Substitute Variables in Symbolic Expressions

Solve the following trigonometric equation using the ReturnConditions option of the solver to obtain the complete solution. The solver returns the solution, parameters used in the solution, and conditions on those parameters.

syms x
eqn = sin(2*x) + cos(x) == 0;
[solx, params, conds] = solve(eqn, x, 'ReturnConditions', true)
solx =
       pi/2 + pi*k
     2*pi*k - pi/6
 (7*pi)/6 + 2*pi*k
 
params =
k
 
conds =
 in(k, 'integer')
 in(k, 'integer')
 in(k, 'integer')

Replace the parameter k with a new symbolic variable a. First, create symbolic variables k and a. (The solver does not create variable k in the MATLAB® workspace.)

syms k a

Now, use the subs function to replace k by a in the solution vector solx, parameters params, and conditions conds.

solx = subs(solx, k, a)
params = subs(params, k, a)
conds = subs(conds, k, a)
solx =
       pi/2 + pi*a
     2*pi*a - pi/6
 (7*pi)/6 + 2*pi*a
params =
a
conds =
 in(a, 'integer')
 in(a, 'integer')
 in(a, 'integer')

Suppose, you know that the value of the parameter a is 2. Substitute a with 2 in the solution vector solx.

subs(solx, a, 2)
ans =
  (5*pi)/2
 (23*pi)/6
 (31*pi)/6

Alternatively, substitute params with 2. This approach returns the same result.

subs(solx, params, 2)
ans =
  (5*pi)/2
 (23*pi)/6
 (31*pi)/6

Substitute parameter a with a floating-point number. The toolbox converts numbers to floating-point values, but it keeps intact the symbolic expressions, such as sym(pi), exp(sym(1)), and so on.

subs(solx, params, vpa(2))
ans =
                               2.5*pi
 3.8333333333333333333333333333333*pi
 5.1666666666666666666666666666667*pi

Approximate the result of substitution with floating-point values by using vpa on the result returned by subs.

vpa(subs(solx, params, 2))
ans =
 7.8539816339744830961566084581988
 12.042771838760874080773466302571
 16.231562043547265065390324146944