Extract duplicate values from both 1st and 2nd column
조회 수: 4 (최근 30일)
이전 댓글 표시
I have a large matrix (120000x4096)to process. There are repetitions in the 1st and 2nd columns. If 2 rows have the same number in the 1st and the 2nd column, only one row is stored. However, if 2 rows have the same number in the 1st columns but different numbers in the 2nd one, both rows are stored. Then extract the other columns related to each set of rows. This can seen in the attached file
Any ideas to do it without a loop please?
Thanks for your help!
댓글 수: 0
채택된 답변
Stephen23
2015년 4월 9일
편집: Stephen23
2015년 4월 20일
Removing duplicate rows, using fully vectorized code, is fast and easy with unique and its 'rows' and 'stable' options:
>> a = [10,10,10;10,10,10;5,5,5;4,4,4]
a =
10 10 10
10 10 10
5 5 5
4 4 4
>> [~,x] = unique(a(:,1:2),'rows','stable');
>> a(x,:)
ans =
10 10 10
5 5 5
4 4 4
Note how indexing is used to select only the first two columns of a as an input to unique, thus the third column is ignored, as the original questions requests that only the first two columns should be compared.
We can also test it on your test data (although putting it in a PDF is a complete pain: please provide text data instead, either within the question itself, or uploaded as a text file):
>> A = [1,2,120; 1,2,120; 1,3,112; 3,5,100; 3,5,100; 3,6,113; 4,2,106; 4,2,106; 4,6,88; 6,11,0; 6,11,0; 6,12,97; 6,12,97]
A =
1 2 120
1 2 120
1 3 112
3 5 100
3 5 100
3 6 113
4 2 106
4 2 106
4 6 88
6 11 0
6 11 0
6 12 97
6 12 97
>> [~,X] = unique(A(:,1:2),'rows','stable');
>> A(X,:)
ans =
1 2 120
1 3 112
3 5 100
3 6 113
4 2 106
4 6 88
6 11 0
6 12 97
Which exactly matches your required output (did I mention that putting the test-case in a PDF is a pain? Please provide plain text instead!)
댓글 수: 3
Image Analyst
2015년 4월 9일
Note, this is valid only for integers. Maybe you posted a simplified case - I don't know - but if you ever need to find matches for floating point numbers, see the FAQ.
추가 답변 (1개)
Thomas Koelen
2015년 4월 9일
편집: Thomas Koelen
2015년 4월 9일
a=[10 10 10; 10 10 10; 5 5 5; 4 4 4];
a =
10 10 10
10 10 10
5 5 5
4 4 4
Code:
a=[10 10 10; 10 10 10; 5 5 5; 4 4 4; 4 4 4];
sizea=size(a);
for i=1:sizea(1,1)
for i2=1:sizea(1,2)
sizea=size(a);
if a(i,i2)==a(i+1,i2)
a(i+1,:)=[];
if i==sizea(1,1)-1
return
end
end
end
end
a =
10 10 10
5 5 5
4 4 4
Where a is your scan matrix!
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!