categorical

Methods

Method Reference: categorical.sort

categorical: B = sort (A)
categorical: B = sort (A, dim)
categorical: B = sort (A, direction)
categorical: B = sort (A, dim, direction)
categorical: B = sort (…, 'MissingPlacement', MP)
categorical: [B, index] = sort (A, …)

Sort elements in a categorical array.

B = sort (A) sorts the categorical array A in ascending order. The sorted array B has the same categories as A. If A is a matrix, sort (A) sorts each column of A in ascending order. For multidimensional arrays, mode (A) sorts along the first non-singleton dimension.

B = sort (A, dim) sorts along the dimension specified by dim.

B = sort (A, direction) also specifies the sorting direction, which can be either 'ascend' (default) or 'descend'.

B = sort (…, 'MissingPlacement', MP) specifies where to place the missing elements (<undefined>) returned in B with any of the following options specified in MP:

  • 'auto', which is the default, places missing elements last for ascending sort and first for descending sort.
  • 'first' places missing elements first.
  • 'last' places missing elements last.

[B, index] = sort (A, …) also returns a sorting index containing the original indices of the elements in the sorted array.

  • If A is a vector, then index contains the original linear indices of the elements in the sorted vector B such that B = A(index).
  • If A is an M×N matrix and dim = 1, then index contains the original row indices of the elements in the sorted vector B such that for j = 1:N, B(:,j) = A(index(:,j),j).

Source Code: categorical

Example: 1

sort orders an ordinal array by its category ranking, not alphabetically by label.

 C = categorical ({'L'; 'S'; 'M'; 'S'; 'L'}, {'S', 'M', 'L'}, 'Ordinal', true)
C =
  5x1 categorical array

    L    
    S    
    M    
    S    
    L
 sort (C)
ans =
  5x1 categorical array

    S    
    S    
    M    
    L    
    L

Any <undefined> values sort to the end by default.