Finding the indices of the elements of one array in another
이전 댓글 표시
Given two vectors A and B, find the index, idx into A of the element of B so that
A(idx)=B.
Now I know there must be many ways it can be done, but is there a one-liner?
For example if
A=[3 4 5 6 7];
B=[6 4 7];
then
[tf,loc]=ismember(A,B);
idx=[1:length(A)];
idx=idx(tf);
idx=idx(loc(tf));
disp(A(idx))
will do it but that is four steps. Is there a more elegant way?
댓글 수: 3
Alan
2011년 12월 3일
Philip
2014년 9월 26일
MATLAB supports logical indexing. No need to use "find":
A = A( ismember( A, B ) );
Leandro Coelho
2016년 7월 1일
Another option: intersect(A,B)
채택된 답변
추가 답변 (6개)
Alan
2011년 12월 3일
댓글 수: 3
Sven
2011년 12월 4일
Alan, well done in asking a question clearly (with code), and in particular taking the time to give feedback on the results above
Iftikhar Ali
2015년 10월 18일
Method 3 has solved my problem, thanks.
David
2020년 1월 18일
Method one also works if there are multiple occurences of B in A. Intersect fails in this case.
Alan
2011년 12월 6일
댓글 수: 2
normanius
2017년 10월 9일
This is by far the best answer!
John Sogade
2020년 1월 2일
obviously this will fail to get A(idx), if any elements of idx are 0 (i.e. B not in A) and robust usage should be clarified to A(idx(idx ~= 0)).
Iftikhar Ali
2015년 10월 18일
1 개 추천
I am facing an issue finding indices of element matching in two arrays.
xpts = [0 0.0004 0.0011 0.0018 0.0025 0.003]; x = 0:0.0001:0.003; index1 = find(ismember(x, xpts));
It returns index1 = [1 5 12 26 31]
but there is one more element '0.0018' in x which also belongs xpts, and not including in the answer.
Similarly when I increase the number of points in x, there are few elements that are missed or not recognized by the find command. What's going wrong here.
Teja Muppirala
2011년 12월 3일
If A is sorted, then I think this is probably the easiest (and also fastest?) way to do it.
[~,idx] = histc(B,A)
If A is not sorted, then:
[As,s_idx] = sort(A);
[~,tmp] = histc(B,As);
idx = s_idx(tmp)
Stephen Politzer-Ahles
2014년 7월 8일
편집: Stephen Politzer-Ahles
2014년 7월 8일
The following should also work for your situation, and just needs one line:
A=[3 4 5 6 7];
B=[6 4 7];
idx = arrayfun( @(x)( find(A==x) ), B );
Junhong YE
2014년 7월 21일
0 개 추천
I think find(ismember(A,B)) would do it.
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!