-
Notifications
You must be signed in to change notification settings - Fork 0
/
findClosestPoint.m
86 lines (81 loc) · 3.07 KB
/
findClosestPoint.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function [closestPointIdx,closestPointDis] = findClosestPoint2(path, X, lastClosestPointIdx)
pathLength = length(path);
x = X(1);
y = X(2);
% t = tic();
% for i = 1:500000
% Avg = 1.2s
% disSquared = (path(:,1) - x).^2 + (path(:,2) - y).^2;
% [~, closestPointIdx] = min(disSquared);
% Avg = 1.7s
% first = max(1,lastClosestPointIdx-100);
% last = min(length(path),lastClosestPointIdx+100);
% section = path([first:last],:);
% disSquared = (section(:,1) - x).^2 + (section(:,2) - y).^2;
% [~, closestPointIdx] = min(disSquared);
% closestPointIdx = closestPointIdx + lastClosestPointIdx - 100 -1;
% Avg = 0.08s
% closestPointIdx = lastClosestPointIdx;
% closestPointDis = (path(closestPointIdx,1) - x).^2 + (path(closestPointIdx,2) - y).^2;
%
% nextIdx = closestPointIdx + 1;
% if nextIdx < pathLength
% nextDis = (path(nextIdx,1) - x).^2 + (path(nextIdx,2) - y).^2;
% while nextDis < closestPointDis
% closestPointIdx = nextIdx;
% closestPointDis = nextDis;
% nextIdx = closestPointIdx + 1;
% if nextIdx > pathLength; break; end
% nextDis = (path(nextIdx,1) - x).^2 + (path(nextIdx,2) - y).^2;
% end
% end
%
% nextIdx = closestPointIdx - 1;
% if nextIdx > 1
% nextDis = (path(nextIdx,1) - x).^2 + (path(nextIdx,2) - y).^2;
% while nextDis < closestPointDis
% closestPointIdx = nextIdx;
% closestPointDis = nextDis;
% nextIdx = closestPointIdx - 1;
% if nextIdx < 1; break; end
% nextDis = (path(nextIdx,1) - x).^2 + (path(nextIdx,2) - y).^2;
% end
% end
% Avg = 0.08s
closestPointIdx = lastClosestPointIdx;
closestPointDis = (path(closestPointIdx,1) - x).^2 + (path(closestPointIdx,2) - y).^2;
idx = lastClosestPointIdx + 1;
attemptsLeft = 30;
while idx < pathLength
dis = (path(idx,1) - x).^2 + (path(idx,2) - y).^2;
if dis < closestPointDis
closestPointIdx = idx;
closestPointDis = dis;
else
attemptsLeft = attemptsLeft - 1;
if attemptsLeft == 0
break
end
end
idx = idx + 1;
end
idx = lastClosestPointIdx - 1;
attemptsLeft = 30;
while idx >= 1
dis = (path(idx,1) - x).^2 + (path(idx,2) - y).^2;
if dis < closestPointDis
closestPointIdx = idx;
closestPointDis = dis;
else
attemptsLeft = attemptsLeft - 1;
if attemptsLeft == 0
break
end
end
idx = idx - 1;
end
% end
% disp([num2str(closestPointIdx), '/', num2str(length(path))])
% toc(t)
closestPointDis = sqrt(closestPointDis);
end