Find same numbers in two vectors

26 Ansichten (letzte 30 Tage)
Robert Schumann
Robert Schumann am 2 Jun. 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

Akzeptierte Antwort

Johannes Fischer
Johannes Fischer am 2 Jun. 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 Kommentare
Robert Schumann
Robert Schumann am 2 Jun. 2021
Thank you very much!!
Johannes Fischer
Johannes Fischer am 2 Jun. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by