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

조회 수: 6(최근 30일)
Tess 2022년 11월 14일
댓글: DGM 2022년 11월 14일
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
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표시숨기기 없음
Walter Roberson 2022년 11월 14일
have you considered calling atan2d()?

댓글을 달려면 로그인하십시오.

### 답변(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')
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'
isdegrees = ismember(lower(angleunits),{'d','deg','degrees'});
if isdegrees
theta = atan2d(y,x);
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표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

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;
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표시숨기기 이전 댓글 수: 1
DGM 2022년 11월 14일
I tend to avoid atan2d(), but I doubt anyone cares about creating that version dependency.

댓글을 달려면 로그인하십시오.

### 범주

Find more on Matrix Indexing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by