Method Reference: string.sort

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

Sort elements in a string array.

B = sort (A) sorts the elements of the string array A in ascending order. Elements are compared lexicographically by their Unicode code points, with the empty string "" sorting before any non-empty string. If A is a matrix, sort (A) sorts each column of A in ascending order. For multidimensional arrays, sort (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 (<missing>) 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: string

Example: 1

sort orders the strings alphabetically.

 s = string ({'pear'; 'apple'; 'fig'; 'banana'})
s =
  4x1 string array

    "pear"      
    "apple"     
    "fig"       
    "banana"
 sort (s)
ans =
  4x1 string array

    "apple"     
    "banana"    
    "fig"       
    "pear"