Best unique maximum matching
显示 更早的评论
I have a rectangular matrix of doubles and I want to pair each column to the row with the best unique maximum, so that if two (or more) columns are paired with the same row then I pair that row with the column having the greatest maximum value among all the paired columns.
If no pairing is possible (if number of columns > number of rows) the algorithm should give back 0 or NaN.
For instance
A=[1 2 3 7;
0 3 4 6;
-1 1 5 3]
sorting it with [B,iB]=sort(A,1,'descend'):
B=
1 3 5 7
0 2 4 6
-1 1 3 3
iB=
1 2 3 1
2 1 2 2
3 3 1 3
What I would like to obtain is the column to row pairing such that:
iRowPaired = [ NaN/0 2 3 1]
Both column 1 and 4 have their maximum in row 1, but since A(1,4)>A(1,1) I pair row 1 only to column 4.
Could someone point me in the right direction for this?
Thanks.
回答(1 个)
Guillaume
2016-11-9
This would work:
[~, iRowPaired] = max(A, [], 1); %faster than sorting
for v = unique(iRowPaired) %iterate over unique values of iRowPaired
vcols = find(v == iRowPaired); %get location of unique value
[~, maxloc] = max(A(v, vcols)); %find which is the maximum at the intersection of the row and multiple columns
vcols(maxloc) = []; %remove column of maximum from list of column
iRowPaired(vcols) = NaN; %and set the remaining columns to NaN
end
2 个评论
Finsteraarhorn
2016-11-9
Guillaume
2016-11-10
Unless I'm misunderstanding something can't you just wrap the above in a loop over the rows of iRowPaired?
[~ iRowPaired] = sort(A, 1, 'descend');
for row = 1 : size(iRowPaired, 1)
for v = unique(iRowPaired(row, :)) %iterate over unique values of current row of iRowPaired
vcols = find(v == iRowPaired(row, :)); %get locations of unique value
[~, maxloc] = max(A(v, vcols)); %find which is the maximum at the intersection of the row and multiple columns
vcols(maxloc) = []; %remove column of maximum from list of column
iRowpaired(row, vcols) = Nan; %and set the remaining columns to NaN
end
end
类别
在 帮助中心 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!