Find same numbers in two vectors

34 views (last 30 days)
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

Accepted Answer

Johannes Fischer
Johannes Fischer on 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 Comments
Johannes Fischer
Johannes Fischer on 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

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!