intersect

Returns the elements that are common to two sets, without duplication.

Syntax

intersect(a,b)

intersect(a,b,'sorted')

intersect(a,b,'stable')

intersect(a,b,'rows')

[c,ia,ib] = intersect(a,b)

Inputs

a, b
The sets whose intersection is to be formed.
Type: double | integer | char | string | logical | struct | cell
Dimension: scalar | string | vector | matrix
'sorted' (Default)
Returns elements of the intersection in ascending order.
Type: string
'stable'
Returns elements of the intersection in their original order.
Type: string
'rows'
Returns common rows as opposed to common elements.
Type: string

Outputs

c
The intersection of a and b.
ia, ib
a(ia) and b(ib) are indiex vectors such that a(ia) = c and b(ib) = c.

Examples

Single return case:

intersect([1,5,2;6,2,6],[9;0;1;2])
ans = [Matrix] 2 x 1
1
2

Multi-return case:

[c,ia,ib]=intersect([1,5,2;6,2,6],[9;0;1;2])
c = [Matrix] 2 x 1
1
2
ia = [Matrix] 2 x 1
1
5
ib = [Matrix] 2 x 1
3
4

Multi-return case with rows option:

intersect([1,5,2;6,2,6],[9,0,1;6,2,6],'rows')
ans = [Matrix] 1 x 3
6  2  6

Comments

When repeated elements occur in an input, the last index will be used.