Is there a way to Rewrite a Symbolic Expression in Terms of nthroot?
6 views (last 30 days)
Show older comments
Suppose I have a symbolic expression
syms x real
g = x^(1/3) - 1
I'd like to evaluate g for negative values of x, either symbolically or numerically with a matlabFunction, and return the real root. But
vpa(subs(g,x,-0.5))
gf = matlabFunction(g);
gf(-0.5)
Instead, what I'd like to have is:
gg = nthroot(x,3) - 1;
vpa(subs(gg,-0.5))
ggf = matlabFunction(gg);
ggf(-0.5)
Suppose g is the result of some other sym operation, so I don't have control over how it's defined.
Is there a simple, automatic, way to change the x^(1/3) to nthroot(x,3). I can do a subs
subs(g,x^(1/3),nthroot(x,3))
But that requires that I know the term(s) I'm subsing for. I want something more generic. So far, the only concept I've thought of is repeated calls to children(), use symFunType to find the power terms, then find those that have the rational exponents with positive denominators, do the nthroot substitution on those, and then reconstruct the expression. I haven't actually tried this yet.
Is there a simpler way, something akin to rewrite(g,'nthroot')?
0 Comments
Accepted Answer
Walter Roberson
on 18 Jul 2023
syms x real
g = x^(1/3) - 1
mapSymType(g, 'power', @(X) nthroot(children(X,1), 1/children(X,2)))
This particular implementation will fail of there are any ^ that are not 1/odd integer. The work-around would be to insert piecewise() checks, like piecewise(mod(1/children(X,2),2)~=0, X, nthroot(children(X,1), 1/children(X,2)))
4 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

