union
Set union: the sorted values that appear in either of two arrays.
Category: Language Fundamentals > Data Types
Syntax
C = union(A, B)
Returns the distinct values in A or B, sorted.
[C, ia, ib] = union(A, B)
Also returns index vectors such that C is built from A(ia) and B(ib).
Description
Duplicates are removed, so the result has each value once, in ascending order for numbers and alphabetical order for text. Both inputs are treated as sets, so their original order and repeated values do not matter.
intersect gives the common values, setdiff the values in one array only, and setxor those in exactly one of them.
Input arguments
A, B- Numeric arrays, cell arrays of character vectors, string arrays, or tables with compatible types.
Output arguments
C- Distinct sorted values (a row if both inputs are rows, otherwise a column).
ia, ib- Indices of the elements taken from
Aand fromB. A value present in both is taken fromA.
Example
Numbers, text and indices
union([3 1 2], [2 5 1])
union({'a','c'}, {'b','a'})
[c, ia, ib] = union([1 2], [2 3])
Output
ans = 1×4
1 2 3 5
ans = 1×3 cell
{'a'} {'b'} {'c'}
c = 1×3
1 2 3
ia = 2×1
1
2
ib = 2