function [numMatches, matches] = ratioTest(desc1, desc2)
% numMatches = ratioTest(desc1, desc2)
% Finds the number of features between two feature sets which pass the ratio test.

THRESHOLD = 0.8;

ann_result = zeros(2*size(desc1, 1), 2);
for i = 1:size(desc1, 1)
    dist = sqrt(sum((repmat(desc1(i, :), size(desc2, 1), 1) - desc2).^2, 2));
    [val, idx] = sort(dist);
    %nearest and second-nearest
    ann_result(2*i-1, 1) = idx(1); %idx
    ann_result(2*i-1, 2) = val(1); %dist
    ann_result(2*i, 1) = idx(2); %idx
    ann_result(2*i, 2) = val(2); %dist
end

%calculate matches
idx = ann_result(:,1);
dist = ann_result(:,2);
idx1 = 1:length(desc1); idx2 = idx(1:2:end)';  %both row vectors
dist1 = dist(1:2:end); dist2 = dist(2:2:end);
idx1_match = idx1(logical(dist1 < THRESHOLD*dist2));
idx2_match = idx2(logical(dist1 < THRESHOLD*dist2));
matches = [idx1_match; idx2_match];
numMatches = numel(matches);

clear ann_result idx idx1 idx2 idx1_match idx2_match matches;