Sorting cell array based on distance

I have two cell arrays that contain information about the x,y,z coordinates for points in space. These data are random and do not necessarily follow any sequence.
Example of data1:
-512.7269 -223.8000 -256.1018
-509.1519 -223.8000 -263.4274
-512.9410 -223.8000 -256.3643
-508.8008 -223.8000 -263.5808
-521.0831 -223.8000 -263.1835
-520.0226 -223.8000 -259.8741
-505.0888 -223.8000 -251.5124
-504.7663 -223.8000 -251.4452
Example of data2:
-500.2925 -178.0828 -260.5501
-500.3713 -177.7340 -259.0459
-500.4465 -177.1616 -257.6118
-500.5162 -176.3785 -256.2803
-500.5790 -175.4029 -255.0823
-500.6334 -174.2572 -254.0454
-500.6780 -172.9680 -253.1935
-500.7120 -171.5645 -252.5458
I am trying to sort the data so that the nearest points in space appear in the same sequence of rows.
This is how the code looks like so far. It calculates the minimum distance for combination of every 2 points and then sort this distance in an ascending fashion. What is missing is the part that updates 'data1' to follow the same sequence.
data1 = importdata ('nodes.txt')
Xi = data1(:,1);
Yi = data1(:,2);
Zi = data1(:,3);
data2 = importdata ('TT_angleBlock_nodes.csv')
Xt = data2(:,1);
Yt = data2(:,2);
Zt = data2(:,3);
input = [Xi,Yi,Zi];
output= [Xt,Yt,Zt];
for row = 1 : 1:row
deltaX = output(row,1) - input(:,1);
deltaY = output(row,2) - input(:,2);
deltaZ = output(row,3) - input(:,3);
% Pythagorean Theorem
distances = sqrt(deltaX .^2 + deltaY .^ 2 + deltaZ .^ 2);
minDistance(row) = min(distances);
Dist = sort (minDistance);
end

 Accepted Answer

KSSV
KSSV on 18 Oct 2021
Read about knnsearch. This will give you the nearest points from a set points for a given point. This will work for you.

4 Comments

Thanks, but can you add a few lines of codes showing how this would help my case?
I have already calculated the Euclidean distance with the current code.
For example, when I run this, I get two arrays with only 1 column. I understand that Idx is the index and D is the distance. What I need is a sorted "input" with 3 columns (x,y,z) sorted in a way so that the smallest distance is achieved.
[Idx,D] = knnsearch(input,output);
I think I figured it out. This is how it should be (I think):
Idx = knnsearch(input,output);
SortedInput = input (Idx,:);
Yes....you got it.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 18 Oct 2021

Commented:

on 18 Oct 2021

Community Treasure Hunt

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

Start Hunting!