union
Set union of two arrays
Syntax
Description
andC
= union(A,B
,___,'rows')
treat each row ofC
= union(A,B
,'rows',___)A
and each row ofB
as single entities and return the combined rows fromA
andB
, with no repetitions. You must specifyA
andB
and optionally can specifysetOrder
.
The'rows'
option does not support cell arrays, unless one of the inputs is either a categorical array or a datetime array.
[
also returns index vectorsC
,ia
,ib
] = union(___)ia
andib
using any of the previous syntaxes.
Generally, the values in
C
are a sorted combination of the elements ofA(ia)
andB(ib)
.If the
'rows'
option is specified, then the rows ofC
are a sorted combination of the rows ofA(ia,:)
andB(ib,:)
.If
A
andB
are tables or timetables, thenC
is a sorted combination of the rows ofA(ia,:)
andB(ib,:)
.
Examples
Union of Two Vectors
定义两个向量的值共同之处。
A = [5 7 1]; B = [3 1 1];
Find the union of vectorsA
andB
.
C = union(A,B)
C =1×41 35 7
Union of Two Tables
Define two tables with rows in common.
A = table([1:5]',['A';'B';'C';'D';'E'],logical([0;1;0;1;0]))
A=5×3 tableVar1 Var2 Var3 ____ ____ _____ 1 A false 2 B true 3 C false 4 D true 5 E false
B = table([1:2:10]',['A';'C';'E';'G';'I'],logical(zeros(5,1)))
B=5×3 tableVar1 Var2 Var3 ____ ____ _____ 1 A false 3 C false 5 E false 7 G false 9 I false
Find the union of tablesA
andB
.
C = union(A,B)
C=7×3 tableVar1 Var2 Var3 ____ ____ _____ 1 A false 2 B true 3 C false 4 D true 5 E false 7 G false 9 I false
Union of Two Vectors and Their Indices
定义两个向量的值共同之处。
A = [5 7 1]; B = [3 1 1];
Find the union of vectorsA
andB
, as well as the index vectors,ia
andib
.
[C,ia,ib] = union(A,B)
C =1×41 35 7
ia =3×13 1 2
ib = 1
The values inC
are the combined values ofA(ia)
andB(ib)
.
Union of Two Tables and Their Indices
Define a table,A
, of gender, age, and height for three people.
A = table(['M';'M';'F'],[27;52;31],[74;68;64],...'VariableNames',{'Gender''Age''Height'},...'RowNames',{'Ted''Fred''Betty'})
A=3×3 tableGender Age Height ______ ___ ______ Ted M 27 74 Fred M 52 68 Betty F 31 64
Define a table,B
with the same variables asA
.
B = table(['F';'M'],[64;68],[31;47],...'VariableNames',{'Gender''Height''Age'},...'RowNames',{'Meg''Joe'})
B=2×3 tableGender Height Age ______ ______ ___ Meg F 64 31 Joe M 68 47
Find the union of tablesA
andB
, as well as the index vectors,ia
andib
.
[C,ia,ib] = union(A,B)
C=4×3 tableGender Age Height ______ ___ ______ Betty F 31 64 Ted M 27 74 Joe M 47 68 Fred M 52 68
ia =3×13 1 2
ib = 2
The data forMeg
andBetty
are the same.union
only returns the index fromA
, which corresponds toBetty
.
Union of Rows in Two Matrices
Define two matrices with a row in common.
A = [2 2 2; 0 0 1]; B = [1 2 3; 2 2 2; 2 2 2];
Find the combined rows ofA
andB
, with no repetition, as well as the index vectorsia
andib
.
[C,ia,ib] = union(A,B,'rows')
C =3×30 0 1 1 2 3 2 2 2
ia =2×12 1
ib = 1
The rows ofC
are the combined rows ofA(ia,:)
andB(ib,:)
.
Union of Two Vectors with Specified Output Order
Use thesetOrder
argument to specify the ordering of the values inC
.
Specify'stable'
if you want the values inC
to have the same order as inA
andB
.
A = [5 7 1]; B = [3 1 1]; [C,ia,ib] = union(A,B,'stable')
C =1×45 7 1 3
ia =3×11 23
ib = 1
Alternatively, you can specify'sorted'
order.
A = [5 7 1]; B = [3 1 1]; [C,ia,ib] = union(A,B,'sorted')
C =1×41 35 7
ia =3×13 1 2
ib = 1
Union of Vectors Containing NaNs
Define two vectors containingNaN
.
A = [5 NaN 1]; B = [4 NaN NaN];
Find the union of vectorsA
andB
.
C = union(A,B)
C =1×61 4 5 NaN NaN NaN
union
treatsNaN
values as distinct.
Cell Array of Character Vectors with Trailing White Space
Create a cell array of character vectors,A
.
A = {'dog','cat','fish','horse'};
Create a cell array of character vectors,B
, where some of the vectors have trailing white space.
B = {'dog ','cat','fish ','horse'};
Combine the elements ofA
andB
.
[C,ia,ib] = union(A,B)
C =1x6 cell{'cat'} {'dog'} {'dog '} {'fish'} {'fish '} {'horse'}
ia =4×12 1 3 4
ib =2×11 3
union
treats trailing white space in cell arrays of character vectors as distinct characters.
Union of Vectors of Different Classes and Shapes
Create a column vector character array.
A = ['A';'B';'C']
A =3x1 char array'A' 'B' 'C'
class(A)
ans ='char'
Create a row vector containing elements of numeric typedouble
.
B = [68 69 70]
B =1×368 69 70
class(B)
ans ='double'
Theunion
ofA
andB
returns a column vector character array.
C = union(A,B)
C =6x1 char array'A' 'B' 'C' 'D' 'E' 'F'
class(C)
ans ='char'
Union of Char and Cell Array of Character Vectors
Create a character vector containing the lettersa
,b
, andc
.
A = ['a';'b';'c']; class(A)
ans ='char'
Create a cell array of character vectors containing the lettersc
,d
, ande
.
B = {'c','d','e'}; class(B)
ans ='cell'
Combine the elements ofA
andB
.
C = union(A,B)
C =5x1 cell{'a'} {'b'} {'c'} {'d'} {'e'}
The result,C
, is a cell array of character vectors.
class(C)
ans ='cell'
Preserve Legacy Behavior of union
Use the'legacy'
flag to preserve the behavior ofunion
from R2012b and prior releases in your code.
Find the union ofA
andB
with the current behavior.
A = [5 7 1]; B = [3 1 1]; [C1,ia1,ib1] = union(A,B)
C1 =1×41 35 7
ia1 =3×13 1 2
ib1 = 1
Find the union ofA
andB
, and preserve the legacy behavior.
A = [5 7 1]; B = [3 1 1]; [C2,ia2,ib2] = union(A,B,'legacy')
C2 =1×41 35 7
ia2 =1×21 2
ib2 =1×23 1
Input Arguments
A,B
—Input arrays
arrays
Input arrays. If you specify the'rows'
option, thenA
andB
must have the same number of columns.
A
andB
must be of the same class with the following exceptions:
logical
,char
, and all numeric classes can combine withdouble
arrays.Cell arrays of character vectors can combine with character arrays or string arrays.
Categorical arrays can combine with character arrays, cell arrays of character vectors, or string arrays.
Datetime arrays can combine with cell arrays of date character vectors or single date character vectors.
There are additional requirements forA
andB
based on data type:
If
A
andB
are both ordinal categorical arrays, they must have the same sets of categories, including their order. If neitherA
norB
are ordinal, they need not have the same sets of categories, and the comparison is performed using the category names. In this case, the categories ofC
consist of the categories ofA
followed by the categories ofB
that are not inA
. The categories are in the same order as inA
andB
秩序是用于排序和类别C
.If
A
andB
are tables or timetables, they must have the same variable names (except for order). For tables, row names are ignored, so that two rows that have the same values, but different names, are considered equal. For timetables, row times are taken into account, so that two rows that have the same values, but different times, are not considered equal.If
A
andB
are datetime arrays, they must be consistent with each other in whether they specify a time zone.
A
andB
also can be objects with the following class methods:
sort
(orsortrows
for the'rows'
option)ne
The object class methods must be consistent with each other. These objects include heterogeneous arrays derived from the same root class. For example,A
andB
can be arrays of handles to graphics objects.
setOrder
—Order flag
'sorted'
(default) |'stable'
Order flag, specified as'sorted'
or'stable'
, indicates the order of the values (or rows) inC
.
Flag | Description |
---|---|
'sorted' |
The values (or rows) in Example C = union([5 5 3],[1 2 5],'sorted')
C = 1 2 3 5 |
'stable' |
The values (or rows) in Example C = union([5 5 3],[1 2 5],'stable')
C = 5 3 1 2 |
Data Types:char
|string
Output Arguments
C
— Combined data ofA
andB
vector | matrix | table | timetable
Combined data ofA
andB
, returned as a vector, matrix, table, or timetable. If the inputsA
andB
are tables or timetables, then the order of the variables inC
is the same as the order of the variables inA
.
The following describes the shape ofC
when the inputs are vectors or matrices and when the'legacy'
flag is not specified:
If the
'rows'
flag is not specified, thenC
is a column vector unless bothA
andB
在这种情况下,行向量吗C
is a row vector. For example,union([],[1 2])
returns a column vector.If the
'rows'
flag is specified, thenC
is a matrix containing the combined rows ofA
andB
.
The class of the inputsA
andB
determines the class ofC
:
If the class of
A
andB
are the same, thenC
is the same class.If you combine a
char
or nondouble numeric class withdouble
, thenC
is the same class as the nondouble input.If you combine a
logical
class withdouble
, thenC
isdouble
.If you combine a cell array of character vectors with
char
, thenC
is a cell array of character vectors.If you combine a categorical array with a character vector, cell array of character vectors, or string, then
C
is a categorical array.If you combine a datetime array with a cell array of date character vectors or single date character vector, then
C
is a datetime array.If you combine a string array with a character vector or cell array of character vectors, then
C
is a string array.
ia
— Index toA
column vector
Index toA
, returned as a column vector when the'legacy'
flag is not specified.ia
indicates the values (or rows) inA
that contribute to the union. If a value (or row) appears multiple times inA
, thenia
contains the index to the first occurrence of the value (or row). If a value appears in bothA
andB
, thenia
contains the index to the first occurrence inA
.
ib
— Index toB
column vector
Index toB
, returned as a column vector when the'legacy'
flag is not specified.ib
indicates the values (or rows) inB
that contribute to the union. If there is a repeated value (or row) appearing exclusively inB
, thenib
contains the index to the first occurrence of the value. If a value (or row) appears in bothA
andB
, thenib
does not contain an index to the value (or row).
Tips
To find the union with respect to a subset of variables from a table or timetable, you can use column subscripting. For example, you can use
union(A(:,
, wherevars
),B(:,vars
))vars
is a positive integer, a vector of positive integers, a variable name, a cell array of variable names, or a logical vector. Alternatively, you can usevartype
to create a subscript that selects variables of a specified type.
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
Usage notes and limitations:
The
'stable'
sorting order is not supported.The
'legacy'
flag is not supported.Inputs of type
char
are not supported.
For more information, seeTall Arrays.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Code generation does not support cell arrays for the first or second arguments.
Code generation does not support
union
between a variable-size rows and columns.A
andB
must be variable-size vector inputs with the same orientation.When you do not specify the
'rows'
option:Inputs
A
andB
must be vectors with the same orientation. If you specify the'legacy'
option, then inputsA
andB
must be row vectors.The first dimension of a variable-size row vector must have fixed length 1. The second dimension of a variable-size column vector must have fixed length 1.
The input
[]
is not supported. Use a 1-by-0 or 0-by-1 input, for example ,zeros(1,0)
, to represent the empty set.If you specify the
'legacy'
选项,然后空outputs are row vectors, 1-by-0. They are never 0-by-0.
When you specify both the
'legacy'
option and the'rows'
option, the outputsia
andib
are column vectors. If these outputs are empty, they are 0-by-1. They are never 0-by-0, even if the outputC
is 0-by-0.When the
setOrder
is not'stable'
or when you specify the'legacy'
option, the inputs must already be sorted in ascending order. The first output,C
, is sorted in ascending order.Complex inputs must be
single
ordouble
.When one input is complex and the other input is real, do one of the following:
Set
setOrder
to'stable'
.Sort the real input in complex ascending order (by absolute value). Suppose the real input is
x
. Usesort(complex(x))
orsortrows(complex(x))
.
SeeCode Generation for Complex Data with Zero-Valued Imaginary Parts(MATLAB Coder).
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Theunion
function partially supports GPU arrays. Some syntaxes of the function run on a GPU when you specify the input data as agpuArray
(Parallel Computing Toolbox). Usage notes and limitations:
The
'legacy'
flag is not supported.64-bit integers are not supported.
For more information, seeRun MATLAB Functions on a GPU(Parallel Computing Toolbox).
Version History
Introduced before R2006a
Ouvrir l'exemple
Vous possédez une version modifiée de cet exemple. Souhaitez-vous ouvrir cet exemple avec vos modifications ?
Commande MATLAB
Vous avez cliqué sur un lien qui correspond à cette commande MATLAB :
Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)