How can do intersection and union of two vectors?

36 次查看(过去 30 天)
Hello everyone, I have two vector A and B :
A=[256 1 6 8 4 5 78 25];
B=[85 22 1 25 2 589 6 3];
I want to have other vector result that consist of the union or the intersection of the elements in A and B like this:
result_union=[256,85,1,22,6,8,25,4,2,5,589,78,25,3];
result_intersect=[1,6,25];
Please, help me how can can I do it?

采纳的回答

Stephen23
Stephen23 2015-6-8
编辑:Stephen23 2015-6-8
Intersection: simply use intersect with the stable option:
>> A = [256,1,6,8,4,5,78,25];
>> B = [85,22,1,25,2,589,6,3];
>> intersect(A,B,'stable')
ans =
1 6 25
Union: to keep the order of the two vectors (like they were zipped or interleaved together), then you could concatenate the vectors and then use unique like this:
>> unique(reshape([A;B],1,[]),'stable')
ans =
256 85 1 22 6 8 25 4 2 5 589 78 3
If the vectors have different lengths then you could use this FEX submission to zip them together (instead of the concatenation and rehsape in my example):

更多回答(1 个)

Titus Edelhofer
Titus Edelhofer 2015-6-8
Hi,
did you try to enter union or intersect in the documentation search? It should give you at least for the intersection a good result ;-).
Regarding the union it depends on if you require exact the ordering that you gave ...
Titus
  2 个评论
Sahar abdalah
Sahar abdalah 2015-6-8
the problem when I use both union and intersect function in matlab is that I get a vector of increasing order then I want to do the union element by element as in the example without order.
result_union= [ 1 2 3 4 5 6 8 22 25 78 85 256 589]
result_intersect = [1 6 25]
Titus Edelhofer
Titus Edelhofer 2015-6-8
There is an ordering parameter for intersect and union:
intersect(A,B, 'stable')
although for union is does not help (directly), since it's using the values from A first and then from B. I guess you need to work it up "by hand".
Titus

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by