Find same numbers in two vectors

35 vues (au cours des 30 derniers jours)
Robert Schumann
Robert Schumann le 2 Juin 2021
Hello,
i need to find same numbers in two vectors and write them down in a third one. Example:
a = [3,8,10,11]
b = [2,3,10,12]
The result should be this vector:
result = [3,10]
Do you have an idea how to do this?
Thanks
Robert

Réponse acceptée

Johannes Fischer
Johannes Fischer le 2 Juin 2021
I think what you need is the ismember function:
a = [3,8,10,11]
b = [2,3,10,12]
result = a(ismember(a, b))
% or
result = b(ismember(b, a))
  2 commentaires
Robert Schumann
Robert Schumann le 2 Juin 2021
Thank you very much!!
Johannes Fischer
Johannes Fischer le 2 Juin 2021
Keep in mind that the results will be different, when a number occurr multiple times
a = [3,8,10,11,3];
b = [2,3,10,10,12];
resultA = a(ismember(a, b))
resultB = b(ismember(b, a))
leads to
resultA =
3 10 3
resultB =
3 10 10
You can avoid this using unique:
resultA = unique(a(ismember(a, b)))
resultB = unique(b(ismember(b, a)))
will lead to
resultA =
3 10
resultB =
3 10

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Computer Vision with Simulink dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by