Find first common element in 2 vectors

10 visualizaciones (últimos 30 días)
ryan
ryan el 4 de Abr. de 2022
Comentada: ryan el 4 de Abr. de 2022
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 comentarios
ryan
ryan el 4 de Abr. de 2022
Editada: ryan el 4 de Abr. de 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 el 4 de Abr. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

David Hill
David Hill el 4 de Abr. de 2022
for k=1:length(A)
c=intersect(A(1:k),B(1:k));
if ~isempty(c)
break;
end
end
  1 comentario
ryan
ryan el 4 de Abr. de 2022
Thank you! This is exactly what I was looking for!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Descriptive Statistics en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by