coordinate angle of a circle

34 Views Asked by At

I have the following Matlab codes to generate a circle for a given radius Rand angle $\theta$,

m = 37; for jj=1:m theta(jj,:) = (2*pi/m).*jj; end R = 1; x = R*cosd(theta); y = R*sind(theta);

Now, suppose I want to back-calculate the angle $\theta$ from the [x,y]coordinate, what is the best way to do it? I have came up with the following code without success, where is the mistake?

% Get theta for ii=1:length(x) if y(ii)>=0 && x(ii)>=0 thetapred(ii) = 180+atand(y(ii)./x(ii)); elseif y(ii)>0 && x(ii)<0 thetapred(ii) = 360-atand(y(ii)./x(ii)); elseif y(ii)<0 && x(ii)<0 thetapred(ii) = atand(y(ii)./x(ii)); elseif y(ii)<0 && x(ii)>0 thetapred(ii) = 180-atand(y(ii)./x(ii)); end end

2

There are 2 best solutions below

10
On BEST ANSWER

Using $\arctan$ you should distinguish two main cases: $x>0$ and $x<0$ and then consider a part $x=0$.

As a simpler alternative you can calculate

  • $\theta =\arccos \left(\frac{x}{\sqrt{x^2+y^2}}\right)$ for $y\ge 0$
  • $\theta =2\pi-\arccos \left(\frac{x}{\sqrt{x^2+y^2}}\right)$ for $y< 0$
0
On

You should use "atan2" function : it has been "invented" to avoid all this fuss by covering at once $[0,2 \pi]$; simply write :

 theta = atan2(y,x)

(Caution: $y$ before $x$).

This function, though deprived of any special mathematical status, can be found in almost all scientific software.