Using FIND for common elements WITHOUT a loop (Vectorized?)

Hello,
I have an array A 100x1 with different datenum that
I need to find in a big array B 5000000x1 (all datenum in B are in A, just repeated many times)
and then replace w another datenum C 100x1 (same index as A)
I am using find( ) but it is taking too long. Is there a way to do this without a loop?
BB=B %making a copy of B to check after.
for i=1:size(A,1)
loc=find(B==A(i))
BB(loc)=C(i);
end

댓글 수: 2

The unique function comes quickly to mind.
The third output from unique may be what you want.
Dave
Dave 2019년 2월 3일
편집: Dave 2019년 2월 3일
thank you, I don't know how to take your comment as the accepted answer.

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

 채택된 답변

Stephen23
Stephen23 2019년 2월 3일

0 개 추천

Use ismember and its second output argument:
>> A = randperm(5)
A =
3 5 4 1 2
>> B = randi(5,1,9)
B =
5 1 2 5 1 2 4 5 4
>> C = (1:5).^2
C =
1 4 9 16 25
>> [~,X] = ismember(B,A);
>> BB = C(X)
BB =
4 16 25 4 16 25 9 4 9

댓글 수: 3

Thanks, is there a way to use that for a matrix instead?
%A is 4x1
A =[1, 6, 5, 5]'
%B is much larger, 6x1
B =[5 5 1 1 1 6 ]'
%A2 is
A2=[101, 501, 601;
102, 502, 602;
103, 503, 603]
% BBB is same dim as B, but using elements from A2
%ANSWER SHOULD BE:
BBB=[501 502 101 102 103 601]'
"Thanks, is there a way to use that for a matrix instead?"
Probably. Please explain the logic of your new example (which is unrelated to your earlier question when C had the same size as A).
Hi Stephen, I really wanted to thank you. I wanted to imporve my really slow code in which I tryz to find a 100k elements in a 320k elements vector. using is memeber the code runs in 5.4832 seconds instead of 1170 seconds when using for and parfor. Vectorization is magical for Big data.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2019년 2월 2일

댓글:

2020년 4월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by