Can I substitute a particular expression?
2 views (last 30 days)
Show older comments
Valeri Aronov
on 23 Jul 2021
Commented: Valeri Aronov
on 24 Jul 2021
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
Accepted Answer
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)]
B = subs(A, k, sigma^2)
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)]
mapSymType(A, 'power', @(expr) piecewise(children(expr,1)==k, sigma^(2*children(expr,2)), expr))
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.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!