I don't know much about reading in stl files but you might want to look into options that would read in the points in different ways to them them in sequential order, if it's possible.
Here are two methods that each produce the same figure shown at the bottom.
th = linspace(0,2*pi,60);
x = sin(th);
y = cos(th);
idx = randsample(numel(x), numel(x));
x = x(idx);
y = y(idx);
idx = convhull(x,y);
figure()
subplot(1,2,1)
plot(x,y,'r-o')
axis square
grid on
title('Original scattered coordinates')
subplot(1,2,2)
plot(x(idx), y(idx), 'r-o')
axis square
grid on
title('Sorted coordinates')
Method 2 shows a solution using proximity. This method relies on the following assumptions:
- The perimeter line does not cross over itself.
- The distance between coordinate A and it's neightboring coordinate B is the minimum distance between coordinate A and any other coordinate in the perimeter execept, perhaps the coordinate that come sequentially before A. In other words, if parts of the parimeter come very close to eachother such that their distance is closer than the interval of coordinates, this will fail.
See inline comments for details.
th = linspace(0,2*pi,60);
x = sin(th);
y = cos(th);
idx = randsample(numel(x), numel(x));
x = x(idx);
y = y(idx);
yIdx = [1,nan(size(y)-1)];
xyTemp = [x(:), y(:)];
xyTemp(1,:) = NaN;
idx = [1, nan(1, numel(x)-1)];
counter = 0;
while any(isnan(idx))
counter = counter+1;
[~, idx(counter+1)] = min(pdist2(xyTemp,[x(idx(counter)), y(idx(counter))]));
xyTemp(idx(counter+1),:) = NaN;
end
figure()
subplot(1,2,1)
plot(x,y,'r-o')
axis square
grid on
title('Original scattered coordinates')
subplot(1,2,2)
plot(x(idx), y(idx), 'r-o')
axis square
grid on
title('Sorted coordinates')
Best Answer