unique values from from two column
8 views (last 30 days)
Show older comments
I have a matrix
A=[1 2 3;
2 4 6;
5 3 2;
8 5 4;
6 7 8]
from this matrix, i want that value in first and second column will not get repeated. For eg. in 1st row 2 is in second column and in second row 2 is in 1st column. Please tell me how we can compare these two rows based on first two column and can get only that row whose value in the third column is greater.
Eg:
Output = [ 2 4 6;
8 5 4;
6 7 8]
Only two column (1, 2) will be compared to get the value from third column.
2 Comments
the cyclist
on 31 Aug 2019
Edited: the cyclist
on 31 Aug 2019
Are you guaranteed that there will be at most two rows with equal values, as in your example? Or could it be like this ...
A=[1 2 3;
2 4 6;
5 2 7]
or like this ...
A=[1 2 3;
2 4 6;
5 2 7;
2 5 4]
Could you have a pattern that connects different rows, like this ...
A=[1 2 3;
2 5 6;
5 1 7]
(note that the 2 and the 5 commingle different rows) or like this ...
A=[5 2 3;
2 5 6]
Could you have equal values in the third column?
A = [1 2 6;
2 5 6];
Which row(s) should be kept?
Accepted Answer
Star Strider
on 31 Aug 2019
The description of your problem is at best ambiguous.
This produces the result you posted:
Output = A(~any(A(:,[2 3]) == 2, 2),:)
produces:
Output =
2 4 6
8 5 4
6 7 8
It obviously tests on the presence of ‘2’ in the second and third columns, since ‘2’ appears to be important here. Note that in row 2 of your desired ‘Output’ matrix, column 3 is less than the other two elements. I see no pattern other than that expressed in my code.
8 Comments
Star Strider
on 2 Sep 2019
Try this:
[C,ia,ib] = intersect(A(:,2),A(:,3),'stable'); % Columns (2,3) Value Intersections
for k = 1:numel(ia)
Ac = {A(ia(k),:), A(ib(k),:)}; % Cell Array Of ‘Matching’ Rows
[~,Ix1] = max([A(ia(k),1), A(ib(k),1)]); % Index Of Maximum Of ‘Ac’
Output(k,:) = Ac{Ix1}; % Preliminary Output Matrix
end
Ix2 = setdiff((1:size(A,1)), [ia; ib]); % Other Rows
Output = [Output; A(Ix2,:)] % Complete Output Matrix
producing:
Output =
29.78 5 8
22.98 4 12
29.94 11 33
13.69 37 38
28.43 17 36
26.97 28 39
29.93 16 45
26.09 40 47
28.61 41 49
29.41 48 50
25.53 26 29
21.43 2 32
29.57 15 35
4.24 18 42
25.83 30 46
My initial intent was to avoid the (explicit) loop, however it turned out to be the best option. (This is a more general version of my earlier code.) When I checked the result, it appears to be correct, although it found one more row (row 1 in my result) than in your example.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!