table

Methods

Method Reference: table.unique

table: tblB = unique (tblA)
table: tblB = unique (tblA, setOrder)
table: tblB = unique (tblA, occurrence)
table: [tblB, ixA, ixB] = unique (…)

Unique rows in a table.

tblB = unique (tblA) returns the unique rows of table tblA in sorted order.

tblB = unique (tblA, setOrder) returns the unique rows of table tblA in a specified order. setOrder can be either 'sorted' (default) or 'stable'.

  • 'sorted' returns the unique rows sorted in ascending order.
  • 'stable' returns the unique rows according to their order of occurrence.

tblB = unique (tblA, occurrence) returns the unique rows of table tblA according to their order of occurrence. occurrence can be either 'first' (default) or 'last'.

  • 'first' returns the first occurrence of each unique row, i.e. the lowest possible indices are returned.
  • 'last' returns the last occurrence of each unique row, i.e. the highest possible indices are returned.

[tblB, ixA, ixB] = unique (…) also returns index vectors ixA and ixB using any of the previous syntaxes. ixA and ixB map the tables tblA and tblB to one another such that tblB = tblA(ixA,:) and tblA = tblB(ixB,:).

Source Code: table

Example: 1

unique removes duplicate rows, comparing whole rows across all variables regardless of their types. By default the surviving rows come back sorted.

 Gender = categorical ({'M'; 'F'; 'M'; 'F'; 'M'});
 State = string ({'NY'; 'CA'; 'NY'; 'CA'; 'NY'});
 Visits = [1; 2; 1; 3; 1];
 T = table (Gender, State, Visits)
T =
  5x3 table

    Gender    State    Visits    
    ______    _____    ______    

         M    "NY"          1    
         F    "CA"          2    
         M    "NY"          1    
         F    "CA"          3    
         M    "NY"          1
 unique (T)
ans =
  3x3 table

    Gender    State    Visits    
    ______    _____    ______    

         F    "CA"          2    
         F    "CA"          3    
         M    "NY"          1

Use 'stable' to keep the rows in their order of first appearance instead, and capture the index vectors relating the inputs to the unique rows.

 [U, ia, ic] = unique (T, 'stable');
 U
U =
  3x3 table

    Gender    State    Visits    
    ______    _____    ______    

         M    "NY"          1    
         F    "CA"          2    
         F    "CA"          3
 ic'
ans =

   1   2   1   3   1