How to find the row numbers of similar elements
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I needed a little help with finding the row numbers of similar elements in a matrix. It involves the use of unique,find and sort commnds but I could not clear the errors that I was facing. My code should do the following:
I have a matrix as follows:
1 3 2
2 4 1
4 3 6
5 1 8
2 8 9
1 7 5
6 6 2
7 9 1
1 3 2
I need my code to first check for similar values in column 1, for example in the above matrix let us consider for the number "1", it occurs three times in column1. So I want my code to check for all the rows in column 1 with a value 1 and then check for the same rows if the corresponding values in column 2 are also same, meaning in the 1st column above the value 1 occurs on rows 1, 6 and 9, then for the same rows the code should check what are the values in column 2, from the matrix it can be noticed that the corresponding values in column 2 for 1 is 3, 7 and 3. After this I need my code to check for the row numbers of similar elemnts that is 3. From the matrix above it is the row numbers 1 and 9. Then I need the code to check for the values in column 3 for rows 1 and 9, if the numbers in column 3 are same then set a variable to 1 otherwise 0. I need the code in a looping structure since I have to check for 50 values.
Any help or suggestions on how to do it is appreciated.
Thanks.
댓글 수: 7
Rik
2019년 11월 20일
Happy to help. If my answer helped you, feel free to mark it as accepted answer.
As for your follow-up question: that would just be simple indexing.
A([1 7],end)=1;
채택된 답변
Rik
2019년 11월 19일
Assuming you want a matrix with the duplicate row indices, the code below should work. It pads the columns with NaN. I slightly adapted your data to test the optimizations.
A=[1 3 2
2 4 1
2 4 1
2 4 1
4 3 6
5 1 8
2 8 9
1 7 5
6 6 2
7 9 1
1 3 2];
[a,b,c]=unique(A,'rows','stable');
z=NaN( numel(c)-numel(b) +1 );%pre-allocate worst-case
hasDuplicates=find( 1 < accumarray([c ones(size(c))],1) );
%slower option:
%for n=reshape(b,1,[])
for n=reshape(hasDuplicates,1,[])
tmp=find(c==n);
if numel(tmp)~=1
z(n,1:numel(tmp))=tmp;
end
end
%remove NaN rows and cols
z(all(isnan(z),2),:)=[];
z(:,all(isnan(z),1))=[];
clc
if ~isempty(z)
disp(z);
else
disp('nothing is found');
end
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Entering Commands에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!