How to find the indices of similar arrays
조회 수: 10 (최근 30일)
이전 댓글 표시
Dear Matlab expertises
I have a large matrix that has some repeated arrays. From this large matrix, I generated a smaller matrix with all unique arrays. Now for each unique array, I would like to find the indices of all similar arrays in the large matrix. I know I may need to use a loop by reading off each unique array in the small matrix and comparing it to the arrays in the large matrix. But the question is how to find the indices of these similar arrays.
Sorry for the long question.
댓글 수: 0
채택된 답변
David Hill
2022년 2월 16일
Do not understand your reference to arrays. Are you talking about row or columns in your matrix? I will assume you are talking about rows and the number of column between large and small matrices are the same.
lmatrix=randi(3,10000,5);
smatrix=unique(randi(3,10,5),'rows');
idx=[];
for k=1:size(smatrix,1)
idx=[idx,find(ismember(lmatrix,smatrix(k,:),'rows'))'];
end
댓글 수: 3
David Hill
2022년 2월 17일
Above should be correct. idx will give you the index of the rows in the large matrix that are the same as the small matrix.
추가 답변 (1개)
Abolfazl Chaman Motlagh
2022년 2월 16일
The function unique return both unique array of input array and the indexes of original array in unique array.
for example :
A = randi([1 5],5,5) % a 5x5 array with just number 1,2,3,4,5
[Unique_A,Unique_index,Indexes] = unique(A);
the Unique_A in above is array of unique elements of A. the Unique_index is index of A which are in Unique_A. and Indexes is index of Unique_A for each elements in A. in other word:
Unique_A = A(Unique_index) and A(:) = Unique_A(Indexes)
so for findind index you can just search in these elements :
Indexes_of_A = Indexes' == Unique_A
by this operation Indexes_of_A is in this example a 5x25 array with in row i, if j-th elements of A ( means A(j)) is i, it is 1, otherwise it is 0. so we can find the linear indexes:
linear_index = cell(numel(Unique_A),1);
all_ind = 1:numel(A); % 1,2,...,25
for i=1:numel(Unique_A)
linear_index{i} = all_ind(Indexes_of_A(i,:));
end
linear_index
you can see for example 11,15 (second row) are linear index of those elements in A which are Unique_A(2) which is 2 here.
you can change the linear index to index of matrix using ind2sub. for example use this instead of last part:
linear_index = cell(numel(Unique_A),1);
all_ind = 1:numel(A); % 1,2,...,25
for i=1:numel(Unique_A)
[row,col]= ind2sub(size(A),all_ind(Indexes_of_A(i,:)));
linear_index{i} = [row' col'];
end
linear_index
now the linear_index{i} is nx2 matrix, the first column are rows and second are cols of indexes.
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!