Если точки расположены так близко друг к другу, вы сможете выполнить трассировку, всегда ища следующую ближайшую точку в списке.
Если бы точка находилась дальше друг от друга, проблема была бы неразрешимой - представьте себе пять точек, где четыре - это углы, а одна - в центре: каков «правильный» способ трассировки линии?
%%# create some points
npts = 100;
x = linspace(-1,1,100)'; %'
y = 1 - x.^2;
pts = [x,y];
%# shuffle the points
newOrder = randperm(npts);
pts = pts(newOrder,:);
%# find index of start, end point
startIdx = find(newOrder == 1);
endIdx = find(newOrder == npts);
%# this brings us to where you are - pts as a nx2 array
%# startIdx indicates the star, and endIdx indicates the triangle.
%# pre-assign output - traceIdx, which contains the ordered indices of the point on the trace
traceIdx = NaN(npts,1);
%# create distance matrix
distances = squareform(pdist(pts));
%# eliminate zero-distance along the diagonal, b/c we don't want points linking to themselves
distances(logical(eye(npts))) = NaN;
%# starting from startIdx: always find the closest next point, store in traceIdx,
%# check whether we've arrived at the end, and repeat if we haven't
done = false;
traceCt = 1;
traceIdx(1) = startIdx;
while ~done
%# find the index of the next, closest point
[dummy,newIdx] = min(distances(traceIdx(traceCt),:));
%# store new index and up the counter
traceCt = traceCt + 1;
traceIdx(traceCt) = newIdx;
%# check whether we're done
if newIdx == endIdx
done = true;
else
%# mask the backward distance so that there's no turning back
distances(newIdx,traceIdx(traceCt-1)) = NaN;
end %# if
end %# while ~done
%# remove NaNs
traceIdx(~isfinite(traceIdx)) = [];
%# plot result with a line connecting the dots to demonstrate that everything went well.
figure,
plot(pts(traceIdx,1),pts(traceIdx,2),'-o')
hold on,
plot(pts(startIdx,1),pts(startIdx,2),'*r')
plot(pts(endIdx,1),pts(endIdx,2),'>g')