Best unique maximum matching
Show older comments
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.
Answers (1)
Guillaume
on 9 Nov 2016
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 Comments
Finsteraarhorn
on 9 Nov 2016
Guillaume
on 10 Nov 2016
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
Categories
Find more on NaNs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!