0
votes

hii i have two matrices in A,B.I want to find k nearest neighbours of A matrix.My matlab code is:

A=[1 2 1;3 4 1;5 6 1;];
  B=[11 12 2;13 4 2;15 16 2;17 18 2;1 2 2;3 4 2;5 6 2;];
  [row,col]=size(A);
  [row1,col1]=size(B);
  dist=zeros(row,row1);
  nnarray = zeros(row,row1);
  k=5;
  nnarray1 = zeros(row,k);
  for i=1:row
  for j=1:row1
        dist(i,j)=sqrt(sum((A(i,:)-B(j,:)).^2));
  end
  [y,index]=sort(dist(i,:));
    nnarray(i,:)=index';
    end

The ouptut matrix for nnarray is: //nearest neighbours of A matrix

5   6   7   2   1   3   4
6   5   7   2   1   3   4
7   6   5   2   1   3   4

Here the output i got only one NEAREST NEIGHBOUR for each element in A matrix. But i want to find 5 nearest neighbours of each element in A i.e 5 nearest neighbours of A(1,1),A(1,2) etc.

How to do it? Where should I modify my code?

2

2 Answers

0
votes

Here the code you have written is correct but to find each for each element you modify here

for i=1:row
for j=1:row1
    dist(i,j)=sqrt(sum((A(1,1)-B(j,:)).^2));
end
end

like that you generalize your code

1
votes

If I understand your question correctly you can just make this modification to your code:

A=[1 2 1;3 4 1;5 6 1;];
B=[11 12 2;13 4 2;15 16 2;17 18 2;1 2 2;3 4 2;5 6 2;];

A = A(:);
B = B(:);

% ... the rest of your code

This will find the nearest neighbour(s) of each element in A in B, where elements of A and B are now in single column order.