MATLAB: Find the closest data point between 2 files by comparing one 3D data point in a file to all 3D data points in another file

nearest coordinates

Hello
Can anyone please help me with this:
I need to compare two files and find the closest x, y, z coordinates for a file A compared to all the points in B
I have 2 files A=> 6982×3 double
First three columns are x, y, z coordinates
part of file A =
50 -4 -46
50 -2 -46
50 0 -46
54 -6 -44
52 -6 -44
50 -6 -44
B=> 751728×4 double
First three columns are x, y, z coordinates , 4th column region information
part of file B =
33 -6 -51 172
-35 -5 -51 172
-34 -5 -51 172
-33 -5 -51 172
33 -5 -51 172
34 -5 -51 172
I need to have something like this fileA coordinates; region info corresponding to closest coordinate; closest coordinate in the File B
I tried this:
D=[]
for i = 1:size(A,1)
M =[A(i,1),A(i,2),A(i,3)];
Mindist=[];
for j = 1:size(HCP,1)
N= [HCP(j,1),HCP(j,2),HCP(j,3)];
distance = sqrt(sum(((M-N).^2),2));
N=[M,distance,HCP(j,4),N];
Mindist=[Mindist;N];
end
[value,ind]= min(Mindist(:,4));
D=[D;Mindist(ind,:)];
end
But I ran into memory issues
then tried :
distances = pdist2(A(:, 1:3), B(:, 1:3));
I got distances matrix but not exactly as what I want, this only gives me pairwise distances.
I am new to matlab can youplease help me with this

Best Answer

Read about knnsearch. This is your function.