Find first common element in 2 vectors

12 views (last 30 days)
I have 2 vectors, A and B, with identical values but in different orders. How do I find the first common element between them? For example, I have 2 vectors as shown below. How would I return the value "25"?
A = [10 25 36 41 53]
B = [53 41 25 10 36]
Thanks in advance for any help!
  4 Comments
ryan
ryan on 4 Apr 2022
Edited: ryan on 4 Apr 2022
Sorry for not providing more context; the actual vectors contain over 2000 values so I just put up a small sample. My vectors are indices after using sort. The contents of each vector are different, but the indices correspond to the same observation. In my example, in vector A, index 10 corresponds to the smallest value and in vector B, index 53 corresponds to the smallest value. I want index 25 because it is the first common index that corresponds to one of the smallest values between both vectors. Please let me know if anything else is unclear. Thanks!
Matt J
Matt J on 4 Apr 2022
I want index 25 because it is the first common index that is smallest in the two vectors.
No, 10 is smaller than 25.

Sign in to comment.

Accepted Answer

David Hill
David Hill on 4 Apr 2022
for k=1:length(A)
c=intersect(A(1:k),B(1:k));
if ~isempty(c)
break;
end
end

More Answers (0)

Categories

Find more on Descriptive Statistics 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!