Cart2pol function: wrong output angle is produced when input angle is in degrees, any help??
9 次查看(过去 30 天)
显示 更早的评论
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
回答(2 个)
DGM
2022-11-14
编辑:DGM
2022-11-14
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.
0 个评论
John D'Errico
2022-11-14
编辑:John D'Errico
2022-11-14
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 个评论
DGM
2022-11-14
I tend to avoid atan2d(), but I doubt anyone cares about creating that version dependency.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Trigonometry 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!