Cart2pol function: wrong output angle is produced when input angle is in degrees, any help??
Mostrar comentarios más antiguos
function [theta, r] = cart2polar(x, y, is_theta_in_deg)
%converts co-ordinates x and y to polar corrdinates r,theta
%is_theta_in_deg is a string variable in this function
%is_theta_in_deg='D' if theta in degrees
%is_theta_in_deg='R' if theta in radians
theta=atan2(y,x);
if is_theta_in_deg=='D'
theta=theta*pi/180;
end
if (is_theta_in_deg=='D')|(is_theta_in_deg=='R')
r=abs(sqrt(x.^2 + y.^2));
else
r=[];
theta=[];
disp('error: third input must be either "D" if input theta is in degrees or "R" if input is in radians otherwise');
end
end
1 comentario
Walter Roberson
el 14 de Nov. de 2022
have you considered calling atan2d()?
Respuestas (2)
Here's one fix and some improvement.
x = 1;
y = 1;
[th r] = cart2polar(x,y,'D')
function [theta, r] = cart2polar(x, y, angleunits)
% [theta, r] = cart2polar(x, y, angleunits)
% converts co-ordinates x and y to polar corrdinates r,theta
%
% angleunits is a char vector or string (case-insensitive)
% valid inputs are 'radians' or 'degrees'
% accepted abbreviations are 'rad','deg', and 'r','d'
isradians = ismember(lower(angleunits),{'r','rad','radians'});
isdegrees = ismember(lower(angleunits),{'d','deg','degrees'});
if isdegrees
theta = atan2d(y,x);
elseif isradians
theta = atan2(y,x);
else
error('some message about the third argument being invalid')
end
r = abs(sqrt(x.^2 + y.^2));
end
I do recall some less explicit ways to allow parameter abbreviation, but I think this will suffice for now. Either way, doing equality matches on char vectors is risky and will easily cause errors.
I'm going to assume that there's little use in returning empty vectors upon error.
John D'Errico
el 14 de Nov. de 2022
Editada: John D'Errico
el 14 de Nov. de 2022
Perhaps your problem is in the conversion of degrees to radians. I think you just took an old code you had written to convert polar coordinates to cartesian. And there you did this:
theta=theta*pi/180;
That will convert degrees to radians. But the OUTPUT of atan2 is already in radians. So instead, you needed
if is_theta_in_deg=='D'
% The RESULT should be degrees, NOT radians
theta=theta*180/pi;
end
That will convert radians to degrees, IF you want a result in degrees.
Really, you should clean up the code too, because the INPUT to your code has nothing to do with degrees or radians. The input to this code is a pair of cartesian coordiantes.
When you hack an old code, make sure you change the ENTIRE code. Don't just change a few lines and hope it will work.
2 comentarios
Image Analyst
el 14 de Nov. de 2022
Or use atand
DGM
el 14 de Nov. de 2022
I tend to avoid atan2d(), but I doubt anyone cares about creating that version dependency.
Categorías
Más información sobre Lengths and Angles en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!