Skip to content

sort

Sorting numbers in an array

B = sort(A)

  • It sorts elements of A in ascending order.
  • If A is a vector, it sorts along the longer dimension.
  • If A is not a vector, it sorts along the first non-singleton dimension.
  • If A is complex, it sorts by modulus, and then by the phase angles if two elements have the same moduli.
  • If A is a character array, it sorts by ASCII values.
  • If A is a logical array, it sorts by the logical values.

Example 1: Sorting a character array consisting of captial letters.

% Random ASCII values of captial letters
a=randi(26,1,20)+64;
% Convert to character array
c=char(a)
% Sorting
sort(c)
c =
MFYEGCVBNICJHOWYIDNV

ans =
BCCDEFGHIIJMNNOVVWYY

B = sort(A, k)

  • Same as B = sort(A) above, except that it sorts elements of A along the k-th non-singleton dimension
  • k should be a positive integer not exceeding ndims(A).

B = sort(A, direction)

  • Same as B = sort(A) above, except that it sorts in the order specified by direction, which is either 'ascend' or 'descend'.

B = sort(A, k, direction)

  • Same as B = sort(A) above, except that it sorts elements of A along the kth non-singleton dimension in the order specified by direction.
  • k and direction are as specified in B = sort(A, k) and B = sort(A, direction).

[B, I] = sort(A)

  • Same as B = sort(A) above, where I contains indices of the sorted elements.

Example 2: Sorting a vector in ascending order along the longer dimension.

A=rand(1,5)
[B,I]=sort(A)
A = 1e-1 ×
8.028   0.054   2.789   7.453   3.767

B = 1e-1 ×
0.054   2.789   3.767   7.453   8.028

I =
2.000   3.000   5.000   4.000   1.000

Example 3: Sorting a matrix in ascending order along the first nonsingleton dimension.

A=rand(3,4)
[B,I]=sort(A)
A = 1e-1 ×
2.568   8.078   3.514   4.341
4.689   4.123   0.316   5.231
2.940   1.377   6.297   9.061

B = 1e-1 ×
2.568   1.377   0.316   4.341
2.940   4.123   3.514   5.231
4.689   8.078   6.297   9.061

I =
1.000   3.000   2.000   1.000
3.000   2.000   1.000   2.000
2.000   1.000   3.000   3.000

[B, I] = sort(A, k)

  • Same as B = sort(A, k) above, where I contains indices of the sorted elements.

[B, I] = sort(A, direction)

  • Same as B = sort(A, direction) above, where I contains indices of the sorted elements.

[B, I] = sort(A, k, direction)

  • Same as B = sort(A, k, direction) above, where I contains indices of the sorted elements.

Example 4: Sorting a matrix in descending order along the second nonsingleton dimension.

A=rand(3,4)
[B,I]=sort(A,2,'descend')
A = 1e-1 ×
3.428   5.493   1.509   0.931
0.481   5.390   2.586   1.182
4.906   0.193   5.493   5.289

B = 1e-1 ×
5.493   3.428   1.509   0.931
5.390   2.586   1.182   0.481
5.493   5.289   4.906   0.193

I =
2.000   1.000   3.000   4.000
2.000   3.000   4.000   1.000
3.000   4.000   1.000   2.000