Can I substitute a particular expression?

2 views (last 30 days)
subexpr() discovers a common subexpression and rewrites a symbolic expression in terms of the found subexpression. How can I similarly rewrite an expression in terms a given subexpression? For example, I would like to use sigma = k^(1/2) to obtain:
sigma, sigma^3, sigma^5
out of
k^(1/2), k^(3/2), k^(5/2)?
  3 Comments
Valeri Aronov
Valeri Aronov on 24 Jul 2021
When I did this:
syms a b c
a = 1 + c^(1/2)
b = 1/c^(1/2)
A1 = subexpr([a, b], 'sigma')
the result was:
A1 = [c^(1/2) + 1, 1/c^(1/2)]
subexpr() does not see the opportunity for sigma to be c^(1/2) let alone in an expression with c^(3/2).
Conclusion: My intent to save on multiple sqrt() calls can't be achieved with current version of subexpr(). I still can do ...^(3/2) and ...^(5/2) once.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 24 Jul 2021
There are two scenarios:
1)
syms k sigma positive
A = [k, k^(1/2), k^(3/2), k^(5/2)]
A = 
B = subs(A, k, sigma^2)
B = 
That is, if necessary you solve() to find a way to express k in terms of sigma, and then subs() into the expression. In this scenario, every k is substituted, not just the ones that have powers. Watch out for the "positive" -- if k could hypothetically be complex or real, then collapasing the exponents might not be correct.
2)
syms k sigma positive
A = [k, k^(1/2), k^(3/2), k^(5/2)]
A = 
mapSymType(A, 'power', @(expr) piecewise(children(expr,1)==k, sigma^(2*children(expr,2)), expr))
ans = 
In this scenario, you only want to affect k that are in power relationships and leave the rest unchanged.
You might perhaps wonder why you would want to leave some unchanged. The answer to that is that your actual situation might have to do with trig being raised to powers, such as wanting to substitute (1-cos(EXPRESSION)^2) for sin(EXPRESSION)^2 while leaving the sin() that are not to powers alone.
  1 Comment
Valeri Aronov
Valeri Aronov on 24 Jul 2021
Magic! Borrowing your code as it is in your 1) for my case produced:
((...)^(1/2))^3 and ((...)^(1/2))^5
but this change
subs(A, k, sigma)
rendered exactly what I wanted.
How can I buy you beer when you come to Sydney? If the country is ever opened again.

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!