Symbolic Variable Substitution Question
1 view (last 30 days)
Show older comments
Hey,
I'm having some issues with the symbolic operators in MATLAB.
Here is the section of code I'm dealing with:
----------------------------------------------------------------------------------------------
syms x y z xs ys zs xs1 xs2 xs3 Q Qdot J Cd xdot ydot zdot r
% Partial Derivative Computations for Range
rho = (x^2+y^2+z^2+xs^2+ys^2+zs^2-2*(x*xs+y*ys)*cos(Q)+2*(x*ys-y*xs)*sin(Q)-2*z*zs)^(1/2);
drho_dx = diff(rho,x);
drho_dx = simplify(drho_dx);
-----------------------------------------------------------------------------------------------
Here is the output
drho_dx = (x - xs*cos(Q) + ys*sin(Q))/(sin(Q)*(2*x*ys - 2*xs*y) - cos(Q)*(2*x*xs + 2*y*ys) - 2*z*zs + x^2 + xs^2 + y^2 + ys^2 + z^2 + zs^2)^(1/2)
Which makes sense. The denominator term is simply rho again so I'd like to substitute in the symbolic variable 'r'. Here's what I've been trying:
subs(drho_dx,(sin(Q)*(2*x*ys - 2*xs*y)-cos(Q)*(2*x*xs + 2*y*ys) - 2*z*zs + x^2 + xs^2 + y^2 + ys^2 + z^2 + zs^2)^(1/2),r)
but the output doesn't change:
ans = (x - xs*cos(Q) + ys*sin(Q))/(sin(Q)*(2*x*ys - 2*xs*y) - cos(Q)*(2*x*xs + 2*y*ys) - 2*z*zs + x^2 + xs^2 + y^2 + ys^2 + z^2 + zs^2)^(1/2)
So I decided to try something different and dropped the one-half power term and went with:
subs(drho_dx,sin(Q)*(2*x*ys - 2*xs*y)-cos(Q)*(2*x*xs + 2*y*ys) - 2*z*zs + x^2 + xs^2 + y^2 + ys^2 + z^2 + zs^2,r)
And now I get:
ans = (x - xs*cos(Q) + ys*sin(Q))/r^(1/2)
Sweet! Now just one more substitution!
subs(ans,(r^(1/2)),r)
ans = (x - xs*cos(Q) + ys*sin(Q))/r^(1/4)
Wait.....what?!
So I pretty much have now idea how to get the ^(1/2) term to substitute in. No idea why as I found an example online that including the power term worked.
Final output should look like this:
(x - xs*cos(Q) + ys*sin(Q))/r
Thoughts? Is there and easier way to do this? I'm just trying to figure out if I'm getting the syntax right.
0 Comments
Answers (1)
Walter Roberson
on 12 Oct 2011
You have in your code
subs(ans,(r^(1/2)),r)
As a "convenience", if subs() does not find the second argument ( r^(1/2) here) in the expression, then it swaps around that argument with the next one and tries again, as if you had written
subs(ans, r, r^(1/2))
Which, if you examine, is exactly what has happened.
Why wasn't r^(1/2) found? Well, consider that the expression
(x - xs*cos(Q) + ys*sin(Q))/r^(1/2)
can be re-written as
(x - xs*cos(Q) + ys*sin(Q)) * r^(-1/2)
After that what you need to know is that the symbolic engine prefers multiplication to division.
What you can do is
subs(ans, r, r^2)
and then the (r^2)^(1/2) would simplify to r provided that you have told MATLAB to assume that r is non-negative (otherwise it is algebraically abs(r) which differs from r if r is negative or complex.)
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!