MATLAB: Find matching rows based on specific column values

arraycolumnsmatrixselection

Hi there, I have a matrix of 3 columns by N rows, e.g:
1 2 5
4 5 7
1 2 9
6 3 2
4 5 1
7 1 3
I want to select all rows where they have the same value in the first and second columns, so for the example above I want:
1 2 5
4 5 7
1 2 9
4 5 1
Any help is appreciated, thanks.

Best Answer

This is rather easy if you know how to address matrices properly. Take your matrix:
>> a=[1 2 5
4 5 7
1 2 9
6 3 2
4 5 1
7 1 3];
Then you need to define the rows, take the first
>> a(1,1:2)
ans =
1 2
Then compare
>> (a(:,1:2)==(a(1,1:2)))
ans =
6×2 logical array
1 1
0 0
1 1
0 0
0 0
0 0
Similarly for the second row
>> (a(:,1:2)==(a(2,1:2)))
ans =
6×2 logical array
0 0
1 1
0 0
0 0
1 1
0 0
And now use an or
>> (a(:,1:2)==(a(1,1:2)))|(a(:,1:2)==(a(2,1:2)))
ans =
6×2 logical array
1 1
1 1
1 1
0 0
1 1
0 0
Finally, you only need one location per row, so use any and then pass that as the address of the rows:
>> a(any((a(:,1:2)==(a(1,1:2)))|(a(:,1:2)==(a(2,1:2))),2),:)
ans =
1 2 5
4 5 7
1 2 9
4 5 1
>>
And your problem is solved!
If it does not, let me know. If it does, please accept the answer