# Find one-to-one correspondence with "knnsearch" function

3 views (last 30 days)
aciara on 1 Feb 2021
Commented: aciara on 4 Feb 2021
Hey everyone!
Is it possible to use the function Idx = knnsearch(X,Y) in order to get a one-to-one correspondence between X and Y? I would like to exclude all values that have been already matched with the nearest neighbor in Idx. If it's not, do you know another way to do that?

Hrishikesh Borate on 4 Feb 2021
Hi,
I understand that you are trying to find one to one correspondence between X and Y. One approach to find it using knnsearch is:-
X = [hospital.Age hospital.Weight];
tempX = X;
Y = [20 162; 30 169; 40 168; 50 170; 60 171];
for i=1:size(Y,1)
Idx = knnsearch(X,Y(i,:));
tempX(Idx,:) = inf;
id(i) = Idx;
end
Another approach is using pdist2 :-
X = [hospital.Age hospital.Weight];
Y = [20 162; 30 169; 40 168; 50 170; 60 171];
D = pdist2(X,Y);
[D,I] = sort(D);
temp = zeros(size(D,1),1);
id = zeros(size(D,2),1);
for i=1:size(D,2)
count = 1;
while(temp(I(count,i))~=1 || id(i)==0)
if temp(I(count,i))==0
temp(I(count,i)) = 1;
id(i) = I(count,i);
else
count = count+1;
end
end
end
aciara on 4 Feb 2021