Cart2pol function: wrong output angle is produced when input angle is in degrees, any help??

조회 수: 8(최근 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
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')
th = 45
r = 1.4142
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
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.

Community Treasure Hunt

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

Start Hunting!

Translated by