How to find the indices of similar arrays
10 views (last 30 days)
Show older comments
Abdulaziz Abutunis
on 16 Feb 2022
Commented: Abdulaziz Abutunis
on 23 Feb 2022
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 Comments
Accepted Answer
David Hill
on 16 Feb 2022
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 Comments
David Hill
on 17 Feb 2022
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.
More Answers (1)
Abolfazl Chaman Motlagh
on 16 Feb 2022
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 Comment
See Also
Categories
Find more on Matrices and Arrays 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!