function [r theta] = calc_circ_angles( xypos )
% function [r theta] = calc_circ_angles( xypos )
%
% Transforms rectangular 2d data into polar coordinates.
%
%    xypos  - Points in 2D space
%    r      - Distance from center of circle
%    theta  - Angles between input vectors and a reference
%
% The xypos data is assumed to be circular.
%
% Nigel Stepp <stepp@atistar.net>
%

if size(xypos,1) == 2
    xypos = xypos';
end;

if size(xypos,2) ~= 2
    disp('xypos data must be 2D');
    return;
end;

datalen = size(xypos, 1);

% find the center of the data and recenter around it
center = mean(xypos);

xypos = [xypos(:,1)-center(1), xypos(:,2)-center(2)];

% Now we can treat each point as a vector.
% Calculate the angle between each vector and a reference

% If we make a vector of reference vectors, we can use
% matlab to do everything at once.

ref = repmat([0,1], datalen, 1);

% first do all of the requisite dot products
dots = dot(xypos, ref, 2);
r = sqrt(dot(xypos, xypos, 2));

% This is the formula for the angle between two vectors
theta = acos( dots./r );

% some of the dots could have been a bit off
theta = real(theta);

