假设你想最小化A的元素和B的匹配元素之间的整体差异,这个问题可以写成分配给每一行(@的元素987654324@) 给定成本矩阵C 的列(B 的元素)。匈牙利(或 Munkres')算法解决了分配问题。
我假设你想最小化 A 和 B 中匹配元素之间的累积平方距离,并使用来自 https://www.mathworks.com/matlabcentral/fileexchange/20652-hungarian-algorithm-for-linear-assignment-problems--v2-3- 的 Yi Cao 的函数 [assignment,cost] = munkres(costMat):
A = [1 5 7];
B = [1 2 3 6 9 10];
[Bprime,matches] = matching(A,B)
function [Bprime,matches] = matching(A,B)
C = (repmat(A',1,length(B)) - repmat(B,length(A),1)).^2;
[matches,~] = munkres(C);
Bprime = B(matches);
end
假设您想递归查找匹配项,正如您的问题所建议的那样,您可以遍历 A,对于 A 中的每个元素,在 B 中找到最接近的剩余元素并丢弃它(sortedmatching 下面);或者您可以迭代地形成并丢弃A 和B 中剩余元素之间的距离最小化匹配,直到A 中的所有元素都匹配(greedymatching):
A = [1 5 7];
B = [1 2 3 6 9 10];
[~,~,Bprime,matches] = sortedmatching(A,B,[],[])
[~,~,Bprime,matches] = greedymatching(A,B,[],[])
function [A,B,Bprime,matches] = sortedmatching(A,B,Bprime,matches)
[~,ix] = min((A(1) - B).^2);
matches = [matches ix];
Bprime = [Bprime B(ix)];
A = A(2:end);
B(ix) = Inf;
if(not(isempty(A)))
[A,B,Bprime,matches] = sortedmatching(A,B,Bprime,matches);
end
end
function [A,B,Bprime,matches] = greedymatching(A,B,Bprime,matches)
C = (repmat(A',1,length(B)) - repmat(B,length(A),1)).^2;
[minrows,ixrows] = min(C);
[~,ixcol] = min(minrows);
ixrow = ixrows(ixcol);
matches(ixrow) = ixcol;
Bprime(ixrow) = B(ixcol);
A(ixrow) = -Inf;
B(ixcol) = Inf;
if(max(A) > -Inf)
[A,B,Bprime,matches] = greedymatching(A,B,Bprime,matches);
end
end
虽然在您的示例中产生相同的结果,但所有三种方法都可能对相同的数据给出不同的答案。