# nearest neighbor implementation matlab

I am trying to implement this research paper:

I understand everything in the paper except the part about the nearest neighbors calculation (section 3).

The only MATLAB function I can think of that makes sense with this research paper squared euclidean distance is the pdist2 function. It would give me the D matrix.

Assuming I am correct, but what is the input to the pdist2 in terms of X and Y? Research paper mentions 100 nearest neighbors and sorted in ascending order, I am assuming this:

[D,I] = pdist2(X,Y,'squaredeuclidean','Smallest',100);

and X and Y is the magnitude spectrogram of the mixture signal. X = Y ?

Also, after I get D matrix, the paper mentions a P matrix of size n x p, I am not sure how to get that matrix from the previous calculation.

After I get that P matrix, I can do the rest of the research paper. So basically, I am just trying to figure out the nearest neighbors calculations D and P.

The author used MATLAB, and I would be happy if someone can provide MATLAB code for this nearest neighbor calculation, just like in the paper.

$D$ is $m \times m$, where $m$ is the total number of time frames in the spectrogram, it represents the squared euclidean distance of each frame to each other frame. In Matlab you could calculate it like this:

% Equation 10
for k = 1:m
for l = 1:m
D(k,l) = sum((X(:,k)-X(:,l)).^2);
end
end


This is clearer from the text than the equation itself.

The $P$ matrix is calculated for each frame from the $p$ the nearest frames to it. The $Y$ matrix is then the median of $P$ at each frame. In matlab you could calculate it like this.

[~,I] = sort(D,2);
for k = 1:m
pNearest = I(k,1:p);
P = X(:,pNearest);
Y(k,:) = median(P,2);
end

• Thank you very much. Just to clarify, the small p is the 100 from the paper right? pNearest = I(k,1:100); ? and also, the small m is the frame number? If so, the dimension of the magnitude spectrogram, so something like [m,n] = size ( magSpec); ? finally, section 4.1 of paper mentions a slight variation with equation 20 using difference matrix T. How does that work? Thank you!
– Dan
Jun 7, 2018 at 23:00
• OK, I tested and it works nicely, the vocals are extracted! :) Now only thing left is to figure out that difference matrix T.
– Dan
Jun 8, 2018 at 2:16