intersect
Elements common to two arrays, without repetition.
Category: Language Fundamentals > Data Types
Syntax
C = intersect(A, B)
Returns the sorted values found in both A and B.
[C, ia, ib] = intersect(A, B)
Also returns index vectors so that C = A(ia) and C = B(ib).
C = intersect(A, B, 'rows')
Treats each row as one element.
C = intersect(___, 'stable')
Keeps the order in which the values appear in A.
Description
Duplicates are collapsed, so each shared value appears once in C. By default the output is sorted. NaN never equals NaN, so it is never reported as common.
The related set operations are union, setdiff and setxor.
Input arguments
A, B- Numeric arrays, cell arrays of character vectors, strings or tables.
'rows'- Compare whole rows of two matrices with the same number of columns.
'sorted' | 'stable'- Order of the result: ascending (default) or order of appearance.
Output arguments
C- Common values. A row vector if both inputs are row vectors, otherwise a column.
ia, ib- Column index vectors into
AandB.
Example
Numbers and text
intersect([1 2 3 4], [3 4 5])
[c, ia, ib] = intersect([5 1 3], [3 5 7])
intersect({'x', 'y', 'z'}, {'z', 'x'})
Output
ans = 1×2
3 4
c = 1×2
3 5
ia = 2×1
3
1
ib = 2×1
1
2
ans = 1×2 cell
{'x'} {'z'}