%FindNLargest.m
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.

%   This is a modified version of Fabien Petitcolas' implementation
%   of Cox's technique by Gabriela Delfino and Fabian Martinez
%
%   Fabien Petitcolas' website: http://petitcolas.net/fabien/

% Put all the elements of the matrix in a vector
n=size(X);
% We first fix the size of the matrix to make 
% the process faster
tmp=zeros(1,n(1)*n(2));
for i=1:n(1)
   for j=1:n(2)
      tmp(j+(i-1)*n(2)) = X(i,j);
   end
end

% The DC coefficient must not be considered into the N largest because % it must not be changed, so we set its value to 0.
tmp(1,1)=0;
% 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
