function [N, D] = mergeResultsWithM(N1, D1, N2, D2, C1, C2, k, m) % Merge neighbors from two sources with a limit on candidate neighbors (m) numQueries = size(N1, 1); % Number of queries in this subset maxCandidates = min(m, size(N1, 2) + size(N2, 2)); % Maximum candidates to consider % Combine distances and neighbors N_combined = [N1, N2 + size(C1, 1)]; % Adjust indices for C2 D_combined = [D1, D2]; % Sort distances and keep only top-m candidates for each query [D_sorted, idx] = sort(D_combined, 2, 'ascend'); D_sorted = D_sorted(:, 1:maxCandidates); % Keep only top-m distances idx = idx(:, 1:maxCandidates); % Keep indices corresponding to top-m distances % Select the corresponding neighbors %N_sorted = N_combined(sub2ind(size(N_combined), ... % repmat((1:numQueries)', 1, maxCandidates), idx)); N_sorted = zeros(numQueries, maxCandidates); % Initialize output for i = 1:numQueries for j = 1:maxCandidates N_sorted(i, j) = N_combined(i, idx(i, j)); end end % Handle cases where m < k if maxCandidates < k % Pad with Inf distances and invalid indices D_sorted = [D_sorted, Inf(numQueries, k - maxCandidates)]; N_sorted = [N_sorted, zeros(numQueries, k - maxCandidates)]; end % Extract top-k from the reduced set of candidates [D, idx_final] = sort(D_sorted, 2, 'ascend'); D = D(:, 1:k); % Final top-k distances %N = N_sorted(sub2ind(size(N_sorted), ... % repmat((1:numQueries)', 1, k), idx_final(:, 1:k))); % Extract top-k neighbors using a loop N = zeros(numQueries, k); % Initialize output for i = 1:numQueries for j = 1:k N(i, j) = N_sorted(i, idx_final(i, j)); end end end