Abbreviate Common Terms in Long Expressions
Long expressions often contain several instances of the same subexpression. Such expressions look shorter if the same subexpression is replaced with an abbreviation. You can use
sympref to specify whether or not to use abbreviated output format of symbolic expressions in live scripts.
For example, solve the equation using
syms x sols = solve(sqrt(x) + 1/x == 1, x)
solve function returns exact solutions as symbolic expressions. By default, live scripts display symbolic expressions in abbreviated output format. The symbolic preference setting uses an internal algorithm to choose which subexpressions to abbreviate, which can also include nested abbreviations. For example, the term contains the subexpression abbreviated as . The symbolic preference setting does not provide any options to choose which subexpressions to abbreviate.
You can turn off abbreviated output format by setting the
'AbbreviateOutput' preference to
false. The returned result is a long expression that is difficult to read.
The preferences you set using
sympref persist through your current and future MATLAB® sessions. Restore the default values of
'AbbreviateOutput' by specifying the
subexpr is another function that you can use to shorten long expressions. This function abbreviates only one common subexpression, and unlike
sympref, it does not support nested abbreviations. Like
subexpr also does not let you choose which subexpressions to replace.
Use the second input argument of
subexpr to specify the variable name that replaces the common subexpression. For example, replace the common subexpression in
sols with the variable
[sols1,t] = subexpr(sols,'t')
subexpr do not provide a way to choose which subexpressions to replace in a solution, you can define these subexpressions as symbolic variables and manually rewrite the solution.
For example, define new symbolic variables
syms a1 a2
Rewrite the solutions
sols in terms of
a2 before assigning the values of
a2 to avoid evaluating
sols = [(1/2*a1 + 1/3 + sqrt(3)/2*a2*1i)^2;... (1/2*a1 + 1/3 - sqrt(3)/2*a2*1i)^2]
Assign the values and to
a1 = t + 1/(9*t)
a2 = t - 1/(9*t)
subs. The result is identical to the first output in this example.
sols_eval = subs(sols)