Abbreviate Common Terms in Long Expressions

Often, long expressions contain several instances of the same subexpression. Such expressions look shorter if you replace the subexpression with an abbreviation. For example, solve this equation.

syms x
s = solve(sqrt(x) + 1/x == 1, x) 
s =
 (1/(18*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
 (3^(1/2)*(1/(9*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
 (25/54 - (23^(1/2)*108^(1/2))/108)^(1/3))*1i)/2 +...
 (25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)/2 + 1/3)^2
 ...
 ((3^(1/2)*(1/(9*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
 (25/54 - (23^(1/2)*108^(1/2))/108)^(1/3))*1i)/2 + 1/(18*(25/54 -...
 (23^(1/2)*108^(1/2))/108)^(1/3)) +...
 (25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)/2 + 1/3)^2

The returned result is a long expression that might be difficult to parse. To represent it in a more familiar typeset form, use pretty. When displaying results, the pretty function can use abbreviations to shorten long expressions.

pretty(s) 
/ /   1          #2   1 \2 \
| | ----- - #1 + -- + - |  |
| \ 18 #2         2   3 /  |
|                          |
| /        1     #2   1 \2 |
| | #1 + ----- + -- + - |  |
\ \      18 #2    2   3 /  /

where

                 /   1       \
         sqrt(3) | ---- - #2 | 1i
                 \ 9 #2      /
   #1 == ------------------------
                     2

         / 25   sqrt(23) sqrt(108) \1/3
   #2 == | -- - ------------------ |
         \ 54           108        /

pretty uses an internal algorithm to choose which subexpressions to abbreviate. It also can use nested abbreviations. For example, the term #1 contains the subexpression abbreviated as #2. This function does not provide any options to enable, disable, or control abbreviations.

subexpr is another function that you can use to shorten long expressions. This function abbreviates only one common subexpression and, unlike pretty, it does not support nested abbreviations. It 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 s by variable t.

[s1,t] = subexpr(s,'t')
s1 =
 (1/(18*t^(1/3)) - (3^(1/2)*(1/(9*t^(1/3)) -...
 t^(1/3))*1i)/2 + t^(1/3)/2 + 1/3)^2
 ...
 ((3^(1/2)*(1/(9*t^(1/3)) - t^(1/3))*1i)/2 +...
 1/(18*t^(1/3)) + t^(1/3)/2 + 1/3)^2

t = 
25/54 - (23^(1/2)*108^(1/2))/108

For the syntax with one input argument, subexpr uses variable sigma to abbreviate the common subexpression. Output arguments do not affect the choice of abbreviation variable.

[s2,sigma] = subexpr(s)
s2 =
 (1/(18*sigma^(1/3)) - (3^(1/2)*(1/(9*sigma^(1/3)) -...
 sigma^(1/3))*1i)/2 + sigma^(1/3)/2 + 1/3)^2
 ...
 ((3^(1/2)*(1/(9*sigma^(1/3)) - sigma^(1/3))*1i)/2 +...
 1/(18*sigma^(1/3)) + sigma^(1/3)/2 + 1/3)^2

sigma = 
25/54 - (23^(1/2)*108^(1/2))/108