% Cartesian2Polar.m
% For any given point in 2D, this script converts from Cartesian
% coordinates to polar coordinates.
% Input the x and y coordinates of the point separately.
% The output angle must be given in degrees, and is required to be 
% in the semi-open interval: [ 0, 360 ).
% There must be no negative angles, 
% and no angles greater than or equal to 360.
% Make sure that your program works for any point in the finite
% 2D plane. Check for any special or usual input point.
% 
% You may use these two functions: sqrt (the positive square root) and 
% atand (the inverse tan of a number measured in degrees).
% However, you cannot use the library function atan2,
% except for checking purposes if you want.
% 
% K. Ming Leung, September 26, 2008.

%%% For 3 pts each:
% Need to check if the following 9 cases give the correct results:
% 1. x = 1, y = 1 gives thetaD = 45
% 2. x = -1, y = 1 gives thetaD = 135
% 3. x = -1, y = -1 gives thetaD = 225
% 4. x = 1, y = -1 gives thetaD = 315
% 5. x = 0, y = 1 gives thetaD = 90
% 6. x = 0, y = -1 gives thetaD = 270
% 7. x = 1, y = 0 gives thetaD = 0
% 8. x = -1, y = 0 gives thetaD = 180
% 9. x = 0, y = 0 gives thetaD = 0

%%% For 3 pts:
% See if the program is written efficiently, no redundant checks.
% Proper use of the if-elseif-else structure.
% Proper use of nesting ifs.

clear;
x = input('Enter the x-coordinate: ');
y = input('Enter the y-coordinate: ');

r = sqrt(x*x+y*y);  % radius r
if x == 0 
    if y > 0
        thetaD = 90;
    elseif y < 0
        thetaD = 270;
    else
        disp('The angle of a zero vector is not defined!');
        thetaD = 0;   % we follow most software to assign a 0.
    end
else
    if x > 0
        if y >=0
            thetaD = atand(y/x);
        else
            thetaD = 360 + atand(y/x);
        end
    else
        thetaD = 180 + atand(y/x);
    end
end
disp('radius = '); disp(r);
disp('angle (in degrees) = '); disp(thetaD);

% No need to do the following check with MATLAB's answer:

angleMatlab = 180*atan2(y,x)/pi;
if angleMatlab < 0
    angleMatlab = 360 + angleMatlab;
end
disp('angle computed using atan2 in MATLAB (in degrees): '); 
disp(angleMatlab)
