function INDEX = FindNLargest(X, N)
%FINDNLARGEST Find largest values in a matrix or a vector
%   INDEX = FINDNLARGEST(X, N) find the N largest values of X
%   and returns their indices in X.

%   Fabien A.P. Petitcolas 27-11-97
%   Copyright (c) 1997 by the University of Cambridge
%   $Revision: 0.2$

% Naive and slow implementation :-(

% Put all the elements of the matrix in a vector
n=size(X);
for i=1:n(1)
   for j=1:n(2)
      tmp(j+(i-1)*n(2)) = X(i,j);
   end
end

% Sort the element of the vector
[tmp, index] = sort(tmp);
l = length(index);

% Take the N largest
for k=1:N
   j = mod(index(l+1-k),n(2));
   if j==0
      j = n(2);
   end
   i = floor((index(l+1-k) - 1) / n(2)) + 1;
   INDEX(1,k) = i;
   INDEX(2,k) = j;
end