Find same numbers in two vectors

30 次查看(过去 30 天)
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

采纳的回答

Johannes Fischer
Johannes Fischer 2021-6-2
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 个评论
Johannes Fischer
Johannes Fischer 2021-6-2
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Downloads 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by