How to accelerate the process of `find` in large for loop ?

조회 수: 3 (최근 30일)
wei zhang
wei zhang 2020년 7월 22일
댓글: wei zhang 2020년 7월 23일
I have two arrays A,B. I want to find the index of every element of B in A. I'm sure that every element of B must appears in A twice. The code of mini case is as below.
A = [1 2 3 4 5 6 5 4 2 7];
B = [2 4 5];
result = zeros(length(B),2);
for i=1:length(B)
result(i,:) = find(A==B(i));
end
% result should be [2,9;4,8;5,7]
The A and B in practice is very large (8000000). It takes long time in this for loop way. Is there any way to improve the code?
I had tried to use ismember function. But it seems I could not bypass the find function.
[ia,ib] = ismember(A,B);
result = zeros(length(B),2);
for i=1:length(B)
result(i,:) = find(ib==i);
end
I know I could use parallel computing toolbox. I just want a more delicated coding way.

채택된 답변

Stephen23
Stephen23 2020년 7월 22일
>> [X,Y] = ismember(A,B);
>> [~,Z] = sort(Y(X));
>> V = find(X);
>> R = reshape(V(Z),2,[]).'
R =
2 9
4 8
5 7
  댓글 수: 1
wei zhang
wei zhang 2020년 7월 23일
How could you understand the appilication of these functions, sort ismember reshape unique, so well?! Your answer is so good! Even I know the meaning of the above functions, I still can't use them properly, for several years!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mehmed Saad
Mehmed Saad 2020년 7월 22일
Try the following code
A = [1 2 3 4 5 6 5 4 2 7];
B = [2 4 5];
[r,c] = find(A-B'==0);
[~,ic] = sort(A(c));
c(ic)
  댓글 수: 1
wei zhang
wei zhang 2020년 7월 23일
Because my size of A and B are very large, the matrix A-B' is out of memory very severely, unfortunately.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by