calculating zig zags from simple path analysis with XY input data

5 views (last 30 days)
Hello, I was looking for code that, given X and Y coordinate vectors would be able to calculate:
speed (euclidean distance between 2 points over time - this part is easy),
directionality (e.g., number of turns greater than 90 degrees).
The code I started with is below, but I don't think it is accurate.
% X = x-axis data
%Y = y-axis data
t=length(X)-1;
c=zeros(t,1);
D=zeros(t,1);
E=zeros(t,1);
for i=1:t
c(i)=dot(X(i:i+1),Y(i:i+1))/norm(X(i:i+1))*norm(Y(i:i+1));
c(i)=acos(c(i))*180/pi;
c(i)=imag(c(i));
end
c=c-360;
for i=2:t
D(i-1)= c(i)-c(i-1);
if D(i-1)>0.5
E(i-1)=1;
end
end
with this, E gives the number of turns that are greeater than 180 degrees. I am not sure if this is the best approach, any thoughts would be most welcome.

Answers (1)

David Young
David Young on 22 Jun 2011
I believe this does what you are asking, but you should check it against some trial data. It counts turns which exceed 90 degrees.
directions = atan2(diff(Y), diff(X)); % direction of each leg
ddiff = diff(directions); % angle at each corner
angle = mod(ddiff+pi, 2*pi) - pi; % ... in range -pi to pi
E = abs(angle) > pi/2; % turns exceeding 90 degrees
nturns = sum(E)
You should find the code straightforward to follow, except for the third line, which is a little more subtle. It deals with the fact that a direction of -179 degrees is close to a direction of +179 degrees. If you experiment you should see that this manipulation deals correctly with such cases, and small changes in direction get mapped to small numbers.

Community Treasure Hunt

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

Start Hunting!