union

Returns the elements contained in either of two sets, without duplication.

Syntax

union(a,b)

union(a,b,'sorted')

union(a,b,'stable')

union(a,b,'rows')

[c,ia,ib] = union(...)

Inputs

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

Outputs

c
The union of a and b.
ia, ib
a(ia) and b(ib) are disjoint sets whose union is c.

Examples

Single return case:
union([1,5,2;6,2,6],[9;0;1;2])
ans = [Matrix] 6 x 1
0
1
2
5
6
9
Multi-return case:
[c,ia,ib] = union([1,5,2;6,2,6],[9;0;1;2])
c = [Matrix] 6 x 1
0
1
2
5
6
9
ia = [Matrix] 2 x 1
3
6
ib = [Matrix] 4 x 1
2
3
4
1
Multi-return case with rows option:
[c,ia,ib]=union([1,5,2;6,2,6],[9,0,1;6,2,6],'rows')
c = [Matrix] 3 x 3
1  5  2
6  2  6
9  0  1
ia = 1
ib = [Matrix] 2 x 1
2
1

Comments

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