Changing the output of a solve function

3 views (last 30 days)
Hello,
I have a question regarding the solve function and symbolic variables.
I have the following code :
syms a b r beta_3s
det_F1=(b*cos(beta_3s) - a*sin(beta_3s))/(r*sin(beta_3s))
sol = solve(det_F1==0,beta_3s,'Real',true)
When it is solved, I get the following solution:
sol =
-2*atan((a + (a^2 + b^2)^(1/2))/b)
-2*atan((a - (a^2 + b^2)^(1/2))/b)
However, I would like my solution to be in the following form
sol = atan2(b,a)
Is there a way to do this?
Thank you

Accepted Answer

John D'Errico
John D'Errico on 11 Jun 2020
Edited: John D'Errico on 11 Jun 2020
You probably won't like this solution, but it is fully valid, as long as you recognize that for ANY value of x, atan(x) is identically the same as atan2(x,1).
So, if you have a solution in the form you got, you can happily just rewrite in the form I show, and VOILA! You now have it in the form of atan2.
I think you want MATLAB to automatically know that the solution you really wanted was this one:
sol = [-2*atan2(a + (a^2 + b^2)^(1/2),b)
-2*atan2(a - (a^2 + b^2)^(1/2),b)]
where you want MATLAB to recognize the purpose of atan2, which is to handle just such a fraction, providing a 4 quadrant result. That means, it needs to recognize the argument to atan would be a fraction, and then to extract the numerator and denominator, splitting them into distinct arguments for atan2.
I think that will be more difficult. Yes, you could take the expression apart yourself, perhaps using a tool like children to split the argument of atan into a numerator and denominator. Then reform it, using atan2.
I would note that atan2 is NOT one of the options for rewrite.
Copy and paste is so much easier. That is, since you know the form of the solution you want to see, just do it yourself. Sometimes convincing a computer to do the obvious in terms of symbolic computations is hardly worth the effort.

More Answers (1)

Walter Roberson
Walter Roberson on 20 Jun 2020
It can be done with mapSymType
mapSymType(sol, 'atan', @fixup_atan2)
function at2 = fixup_atan2(v)
cv = children(v); %strip atan call
[n, d] = numden(cv);
at2 = atan2(n, d);
end
If you really need to it could be done with anonymous function calls instead of a real function, but using a real function makes the code a lot easier; you cannot use simple children() to get the numerator and denominator because you would not want to assume that the expression will be in the form of a division.

Community Treasure Hunt

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

Start Hunting!