Sort array elements
collapse all in page
Syntax
B = sort(A)
B = sort(A,dim)
B = sort(___,direction)
B = sort(___,Name,Value)
[B,I] =sort(___)
Description
B = sort(A)
sorts the elements of A
. By default, sort
uses ascending sorted order.
If
A
is a vector, thensort(A)
sortsthe vector elements.If
A
is a matrix, thensort(A)
treatsthe columns ofA
as vectors and sorts each column.If
A
is a multidimensional array,thensort(A)
operates along the first array dimensionwhose size does not equal 1, treating the elements as vectors.
example
B = sort(A,dim)
returnsthe sorted elements of A
along dimension dim
.For example, if A
is a matrix, then sort(A,2)
sortsthe elements of each row.
example
B = sort(___,direction)
returnssorted elements of A
in the order specified by direction
usingany of the previous syntaxes. 'ascend'
indicatesascending order (the default) and 'descend'
indicatesdescending order.
example
B = sort(___,Name,Value)
specifiesadditional parameters for sorting. For example, sort(A,'ComparisonMethod','abs')
sortsthe elements of A
by magnitude.
example
[B,I] =sort(___)
also returns a collection of indexvectors for any of the previous syntaxes. I
isthe same size as A
and describes the arrangementof the elements of A
into B
alongthe sorted dimension. For example, if A
is a vector,then B = A(I)
.
example
Examples
collapse all
Sort Vector in Ascending Order
Open Live Script
Create a row vector and sort its elements in ascending order.
A = [9 0 -7 5 3 8 -10 4 2];B = sort(A)
B = 1×9 -10 -7 0 2 3 4 5 8 9
Sort Matrix Rows in Ascending Order
Open Live Script
Create a matrix and sort each of its rows in ascending order.
A = [3 6 5; 7 -2 4; 1 0 -9]
A = 3×3 3 6 5 7 -2 4 1 0 -9
B = sort(A,2)
B = 3×3 3 5 6 -2 4 7 -9 0 1
Sort Matrix Columns in Descending Order
Open Live Script
Create a matrix and sort its columns in descending order.
A = [10 -12 4 8; 6 -9 8 0; 2 3 11 -2; 1 1 9 3]
A = 4×4 10 -12 4 8 6 -9 8 0 2 3 11 -2 1 1 9 3
B = sort(A,'descend')
B = 4×4 10 3 11 8 6 1 9 3 2 -9 8 0 1 -12 4 -2
Sort String Array
Open Live Script
Starting in R2017a, you can create string arrays using double quotes, and sort them using the sort
function. Sort strings in each column of a string array according to Unicode® dictionary order.
A = ["Santos","Burns"; ... "Jones","Morita"; ... "Petrov","Adams"];B = sort(A)
B = 3x2 string "Jones" "Adams" "Petrov" "Burns" "Santos" "Morita"
Sort the strings in each row.
B = sort(A,2)
B = 3x2 string "Burns" "Santos" "Jones" "Morita" "Adams" "Petrov"
Sort and Index datetime
Array
Open Live Script
Create an array of datetime
values and sort them in ascending order, that is, from the earliest to the latest calendar date.
ds = {'2012-12-22';'2063-04-05';'1992-01-12'};A = datetime(ds,'Format','yyyy-MM-dd')
A = 3x1 datetime 2012-12-22 2063-04-05 1992-01-12
[B,I] = sort(A)
B = 3x1 datetime 1992-01-12 2012-12-22 2063-04-05
I = 3×1 3 1 2
B
lists the sorted dates and I
contains the corresponding indices of A
.
Access the sorted elements from the original array directly by using the index array I
.
A(I)
ans = 3x1 datetime 1992-01-12 2012-12-22 2063-04-05
Sort Vectors in Same Order
Open Live Script
Create two row vectors that contain related data in the corresponding elements.
X = [3 6 4 2 1 5];Y = ["yellow" "purple" "green" "orange" "red" "blue"];
First sort the vector X
, then sort the vector Y
in the same order as X
.
[Xsorted,I] = sort(X)
Xsorted = 1×6 1 2 3 4 5 6
I = 1×6 5 4 1 3 6 2
Ysorted = Y(I)
Ysorted = 1x6 string "red" "orange" "yellow" "green" "blue" "purple"
Sort 3-D Array
Open Live Script
Create a 2-by-2-by-2 array and sort its elements in ascending order along the third dimension.
A(:,:,1) = [2 3; 1 6];A(:,:,2) = [-1 9; 0 12];A
A = A(:,:,1) = 2 3 1 6A(:,:,2) = -1 9 0 12
B = sort(A,3)
B = B(:,:,1) = -1 3 0 6B(:,:,2) = 2 9 1 12
Use A(:)
, the column representation of A
, to sort all of the elements of A
.
B = sort(A(:))
B = 8×1 -1 0 1 2 3 6 9 12
Complex Vector
Open Live Script
Sort the elements of a complex vector by their real parts. By default, the sort
function sorts complex values by their magnitude, and breaks ties using phase angles. Specify the value of 'ComparisonMethod'
as 'real'
to instead sort complex values by their real parts. For elements with equal real parts, sort
breaks the tie based on their imaginary parts.
A = [1+2i 3+1i 1i 0 -1i];B = sort(A,'ComparisonMethod','real')
B = 1×5 complex 0.0000 - 1.0000i 0.0000 + 0.0000i 0.0000 + 1.0000i 1.0000 + 2.0000i 3.0000 + 1.0000i
Input Arguments
collapse all
A
— Input array
vector | matrix | multidimensional array
Input array, specified as a vector, matrix, or multidimensional array.
If
A
is a scalar, thensort(A)
returnsA
.If
A
is complex, then by default,sort
sortsthe elements by magnitude. If more than one element has equal magnitude,then the elements are sorted by phase angle on the interval (−π,π].If
A
is a cell array of charactervectors or a string array, thensort(A)
sorts theelements according to the code order for the UTF-16 character encodingscheme. The sort is case-sensitive. For more information on sortingcharacter and string arrays, see Sort Order for Character and String Arrays.If
A
is a string array, thensort
reordersthe elements of the array, but does not reorder characters withinthe strings.If
A
is a categorical array, then the sorting order is based on the category order returned bycategories(A)
.
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
| categorical
| datetime
| duration
Complex Number Support: Yes
dim
— Dimension to operate along
positive integer scalar
Dimension to operate along, specified as a positive integerscalar. If no value is specified, then the default is the first arraydimension whose size does not equal 1.
Consider a matrix
A
.sort(A,1)
sortsthe elements in the columns ofA
.sort(A,2)
sorts the elements inthe rows ofA
.
sort
returns A
if dim
isgreater than ndims(A)
. dim
isnot supported when A
is a cell array, that is, sort
onlyoperates along the first array dimension whose size does not equal1.
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
direction
— Sorting direction
'ascend'
(default) | 'descend'
Sorting direction, specified as 'ascend'
or 'descend'
. direction
isnot supported when A
is a cell array, that is, sort
onlysorts in ascending order.
Name-Value Arguments
Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN
, where Name
is the argument name and Value
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name
in quotes.
Example: sort(A,'MissingPlacement','last')
MissingPlacement
— Placement of missing values
'auto'
(default) | 'first'
| 'last'
Placement of missing values (NaN
, NaT
, <undefined>
,and missing
) specified as the comma-separated pairconsisting of 'MissingPlacement'
and one of thefollowing:
'auto'
— Missing elementsare placed last for ascending order and first for descending order.'first'
— Missing elementsare placed first.'last'
— Missing elementsare placed last.
ComparisonMethod
— Element comparison method
'auto'
(default) | 'real'
| 'abs'
Element comparison method for numeric input, specified as the comma-separated pair consisting of 'ComparisonMethod'
and one of the following:
'auto'
— SortA
byreal(A)
whenA
is real, and sort byabs(A)
whenA
is complex.'real'
— SortA
byreal(A)
whenA
is real or complex. IfA
has elements with equal real parts, then useimag(A)
to break ties.'abs'
— SortA
byabs(A)
whenA
is real or complex. IfA
has elements with equal magnitude, then useangle(A)
in the interval (-π,π] to break ties.
Output Arguments
collapse all
B
— Sorted array
vector | matrix | multidimensional array
Sorted array, returned as a vector, matrix, or multidimensional array. B
is the same size and type as A
.
Data Types: double
| single
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64
| logical
| char
| string
| cell
| categorical
| datetime
| duration
I
— Sort index
vector | matrix | multidimensional array
Sort index, returned as a vector, matrix, or multidimensionalarray. I
is the same size as A
.The index vectors are oriented along the same dimension that sort
operateson. For example, if A
is a 2-by-3 matrix, then [B,I]= sort(A,2)
sorts the elements in each row of A
.The output I
is a collection of 1-by-3 row indexvectors describing the rearrangement of each row of A
.
The sort
function uses a stable sorting algorithm. So, when the input contains repeated values, the sort index preserves the original order from the input, regardless of sorting direction. For example, if A = [1 2 1 2]
, then [Ba,Ia] = sort(A,'ascend')
returns the sort index Ia = [1 3 2 4]
and [Bd,Id] = sort(A,'descend')
returns the sort index Id = [2 4 1 3]
.
More About
collapse all
Sort Order for Character and String Arrays
MATLAB® stores characters as Unicode® usingthe UTF-16 character encoding scheme. Character and string arraysare sorted according to the UTF-16 code point order. For the charactersthat are also the ASCII characters, this order means that uppercaseletters come before lowercase letters. Digits and some punctuationalso come before letters.
Tips
The
sortrows
function providesadditional flexibility for subsorting over multiple columns of matrixor table inputs.The
sort
function and the relationaloperators use different orderings for complex numbers. For more information,see Relational Operations.
Extended Capabilities
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function supports tall arrays with the limitations:
You must specify the dimension to sort, as in
sort(X,dim)
.Sorting the tall dimension, as in
sort(X,1)
,is only supported for column vectors.
For more information, see Tall Arrays.
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
If
A
is complex with all zero imaginary parts, then MATLAB might convertA
toreal(A)
before callingsort(A)
. In this case, MATLAB sortsA
byreal(A)
, but the generated code sortsA
byabs(A)
. To make the generated code match MATLAB, usesort(real(A))
orsort(A,'ComparisonMethod','real')
. See Code Generation for Complex Data with Zero-Valued Imaginary Parts (MATLAB Coder).If you supply
dim
, then it must be constant.Variable-sizing support must be enabled when input cell array is heterogeneous.
For limitations related to variable-size inputs, see Variable-Sizing Restrictions for Code Generation of Toolbox Functions (MATLAB Coder).
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Refer to the usage notes and limitations in the C/C++ Code Generation section. The same limitations apply to GPU code generation.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
The sort
function fully supports GPU arrays. To run the function on a GPU, specify the input data as a gpuArray (Parallel Computing Toolbox). For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Distributed Arrays
Partition large arrays across the combined memory of your cluster using Parallel Computing Toolbox™.
Usage notes and limitations:
Table, timetable, and datetime inputs are not supported.
For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).
Version History
Introduced before R2006a
See Also
issorted | max | min | sortrows | unique | topkrows
Topics
- Reshaping and Rearranging Arrays
MATLAB 명령
다음 MATLAB 명령에 해당하는 링크를 클릭했습니다.
명령을 실행하려면 MATLAB 명령 창에 입력하십시오. 웹 브라우저는 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:
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
- Deutsch
- English
- Français
- United Kingdom (English)
Contact your local office