Main Content

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 x+1x=1 using solve.

syms x
sols = solve(sqrt(x) + 1/x == 1, x)
sols = 

(118σ2+σ22+13-σ12118σ2+σ22+13+σ12)where  σ1=319σ2-σ2i2  σ2=2554-231081081/3

The 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 σ1 contains the subexpression abbreviated as σ2. 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.

sols = 


The preferences you set using sympref persist through your current and future MATLAB® sessions. Restore the default values of 'AbbreviateOutput' by specifying the 'default' option.


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 sympref, 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 t.

[sols1,t] = subexpr(sols,'t')
sols1 = 


t = 


Although sympref and 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 a1 and a2.

syms a1 a2

Rewrite the solutions sols in terms of a1 and a2 before assigning the values of a1 and a2 to avoid evaluating sols.

sols = [(1/2*a1 + 1/3 + sqrt(3)/2*a2*1i)^2;...
        (1/2*a1 + 1/3 - sqrt(3)/2*a2*1i)^2]
sols = 


Assign the values (t+19t) and (t-19t) to a1 and a2, respectively.

a1 = t + 1/(9*t)
a1 = 


a2 = t - 1/(9*t)
a2 = 


Evaluate sols using subs. The result is identical to the first output in this example.

sols_eval = subs(sols)
sols_eval = 

(118σ2+σ22+13-σ12118σ2+σ22+13+σ12)where  σ1=319σ2-σ2i2  σ2=2554-231081081/3