Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
MATLAB’s sort function returns a copy of an array with its elements arranged in ascending order by default; sort(A,'descend') reverses the order, and a second output, [B,I] = sort(A), returns the index vector that tells you where each sorted element came from. According to the MathWorks reference, the result B has the same size and type as A, the sort is stable, and missing values such as NaN are placed last in an ascending sort and first in a descending sort unless you say otherwise. This guide covers sorting in MATLAB from the one-line call to the index output, NaN handling and the choice between sort and sortrows. All function behaviour below is taken from the MathWorks documentation read on 2026-11-12.
What it is used for in research
Sorting is a routine step in analysis scripts: ranking values before computing percentiles, ordering samples by a measured quantity, finding the largest or smallest observations, or putting a result table into a reproducible order before it is exported. The index output matters as much as the sorted values, because research data usually lives in several parallel arrays (sample identifiers, measurements, group labels), and sorting one of them means reordering the others in the same way. Related operations on this site include finding unique values in MATLAB, testing membership with ismember, the max command and the median function, all of which interact naturally with sorted data.
How to install or access it
sort is documented in the core MATLAB function reference (the matlab/ref section of the MathWorks help centre), so it is part of the base MATLAB product rather than an add-on toolbox function. MATLAB itself is obtained from MathWorks at mathworks.com/products/matlab.html, or through an institutional licence arranged by your university or employer. No separate installation step is needed to call sort once MATLAB is running. If you do not have access to MATLAB, the free alternatives table below shows how GNU Octave and NumPy handle the same task.
Step-by-step: sorting in MATLAB
Step 1. Sort a vector in ascending order
Create the array and call sort on it. The MathWorks example uses:
A = [9 0 -7 5 3 8 -10 4 2];
B = sort(A)
which returns -10 -7 0 2 3 4 5 8 9. Ascending is the default, so no direction argument is needed.
Step 2. Choose descending order with the direction argument
Pass 'descend' as the direction: B = sort(A,'descend'). The two valid direction values are 'ascend' (the default) and 'descend'. The documentation notes that the direction argument is not supported for cell arrays.
Step 3. Choose the dimension for matrices and arrays
For a matrix, the dim argument selects which dimension to sort along: sort(A,1) sorts each column and sort(A,2) sorts the elements within each row. If you omit dim, MATLAB uses the first array dimension whose size is not 1. The dim value must be a positive integer scalar; if it exceeds the number of dimensions of A, sort returns A unchanged. The dim argument is also not supported for cell arrays.
The full list of syntaxes in the documentation is:
B = sort(A)B = sort(A,dim)B = sort(___,direction)B = sort(___,Name,Value)[B,I] = sort(___)
Step 4. Request the index output
Add a second output to capture the sort index:
X = [3 6 4 2 1 5];
[Xsorted,I] = sort(X)
This returns Xsorted = 1 2 3 4 5 6 and I = 5 4 1 3 6 2. Each entry of I is the position in the original vector of the element now sitting at that place in the sorted result. For a vector, the documentation states the relationship as B = A(I).
Step 5. Reorder a parallel array with the index
The index output lets you apply the same ordering to any other array of the same length. Suppose a second vector holds sample labels for the values in X:
ids = ['a' 'b' 'c' 'd' 'e' 'f'];
[Xsorted,I] = sort(X);
idsSorted = ids(I)
Using I = 5 4 1 3 6 2 from the previous step, ids(I) picks the fifth, fourth, first, third, sixth and second labels, giving edacfb. The label that belonged to the smallest value (e, paired with 1) now comes first. This is an illustrative example constructed from the documentation’s vector, not a dataset.
Step 6. Control where missing values go
Use the MissingPlacement name-value argument, for example sort(A,'MissingPlacement','first'). The accepted values are 'auto' (the default), 'first' and 'last'. With 'auto', missing elements are placed last for an ascending sort and first for a descending sort. The documentation counts NaN, NaT, <undefined> and missing as missing values.
Step 7. Sort complex numbers with ComparisonMethod
For complex data, ComparisonMethod decides what is compared. 'auto' (the default) uses real(A) for real input and abs(A) for complex input. 'real' compares the real parts and uses the imaginary parts to break ties. 'abs' compares magnitudes and uses the phase angle to break ties. The documentation’s example applies sort(A,'ComparisonMethod','real') to A = [1+2i 3+1i 1i 0 -1i].
Output and how to read it
The first output B always has the same size and data type as the input. The second output I has the same size as A and holds indices, not values. Two details are worth reading carefully.
Stability and ties
The documentation states that sort uses a stable sorting algorithm, so equal elements keep their original relative order. Its example uses A = [1 2 1 2]. In ascending order the index is [1 3 2 4]: the two 1s appear in the order they occurred (positions 1 then 3), then the two 2s (positions 2 then 4). In descending order the index is [2 4 1 3]: the 2s come first, still in their original order (2 then 4), followed by the 1s (1 then 3). Notice that descending order is not simply the ascending index reversed; reversing [1 3 2 4] would put position 4 before position 2.
Default direction of missing values
Because missing values go last when ascending and first when descending, a descending sort of data containing NaN puts the NaN entries at the top of the result. If you are taking the first few entries of a descending sort to find the largest observations, either remove missing values beforehand or set 'MissingPlacement','last'.
sort in MATLAB versus sortrows
Use sort when each column (or row) should be ordered independently, and sortrows when whole rows must stay together and be ordered by the contents of one or more columns. The two functions share the same stability, MissingPlacement and ComparisonMethod options, per the MathWorks reference pages.
| Task | Call | What happens |
|---|---|---|
| Order a vector | sort(x) |
Returns elements in ascending order |
| Order each column of a matrix independently | sort(A,1) |
Each column is sorted on its own; rows are no longer intact |
| Order each row independently | sort(A,2) |
The elements within each row are sorted |
| Order whole rows by a key column | sortrows(A,column) |
Rows move together, ordered by the named column |
| Order rows by several keys | sortrows(A,[c1 c2]) |
Columns are listed in priority order; a negative column number means descending |
| Know the original row positions | [B,index] = sortrows(A,___) |
Returns the row index of the sort |
| Order a table by variables | sortrows(tblA,vars) |
Sorts the table rows by the named variables |
For sortrows, a direction argument ('ascend' or 'descend', as a single value or one per column) overrides the sign of any negative column number. In the documentation’s example A = [1 1; 2 2; 1 2; 2 2] sorted by the first column, the row index is [1;3;2;4] ascending and [2;4;3;1] descending, which again demonstrates stability. Timetables are sorted only by their row times.
Troubleshooting
- Rows no longer match after sorting a matrix.
sort(A,1)orders every column independently, which breaks the link between values in the same row. Usesortrowsto keep rows intact. - The matrix came back unchanged. If
dimis larger than the number of dimensions ofA,sortreturnsA. Check that you meant1or2. - An error with direction or dimension on a cell array. Both the
dimanddirectionarguments are listed as unsupported for cell arrays. NaNvalues appear first in a descending result. That is the'auto'default forMissingPlacement; set'last'or'first'explicitly.- Complex values are ordered unexpectedly. The default compares by absolute value for complex input; request
'ComparisonMethod','real'if you want ordering by real part. - Ties are ordered differently from another tool. MATLAB’s sort is stable. Check whether the other tool guarantees stability; the data table below shows that the NumPy default does not.
- You want to sort a timetable by a data column. Per the
sortrowsreference, timetables are sorted only by their row times.
Free alternatives
If MATLAB is not available, GNU Octave and NumPy provide an equivalent operation. The behaviours differ in small but important ways, particularly for descending order, NaN placement and stability, so check them before porting a script.
| Tool | Basic call | Index output | Key difference from MATLAB |
|---|---|---|---|
| GNU Octave | [s,i] = sort(x), with "ascend" or "descend" as the mode |
Second output holds original indices | NaN values are treated as greater than any other value and sorted to the end; the manual does not state descending-mode placement |
| NumPy (Python) | np.sort(a) |
Use np.argsort(a) |
Default kind is quicksort and not guaranteed stable; pass stable=True when ties matter; the descending argument is documented as new in version 2.5 |
The data table below compares the three tools on the same six properties, each traced to the vendor documentation.
FAQ
How do I sort in MATLAB in descending order?
Call sort(A,'descend'). The default direction is 'ascend', and the direction argument is not supported for cell arrays.
How do I get the original positions of sorted values?
Request the second output: [B,I] = sort(A). For a vector, B = A(I), so I can reorder any parallel array of the same length.
Is MATLAB sort stable?
Yes. The MathWorks documentation states that sort uses a stable sorting algorithm, so equal elements keep their original relative order in both ascending and descending sorts.
Where do NaN values go when I sort?
By default ('MissingPlacement','auto'), missing values go last in an ascending sort and first in a descending sort. Use 'first' or 'last' to override.
How do I sort a matrix by one column?
Use sortrows(A,column), which moves whole rows together. A negative column number sorts that column in descending order.
Does sort work on the columns or the rows of a matrix?
With no dim, it works along the first dimension whose size is not 1, which is columns for an ordinary matrix. sort(A,2) sorts within rows.
Sources
- MathWorks, sort (MATLAB documentation), read 2026-11-12.
- MathWorks, sortrows (MATLAB documentation), read 2026-11-12.
- GNU Octave manual, Rearranging Matrices (sort), read 2026-11-12.
- NumPy documentation, numpy.sort, read 2026-11-12.
Data: Sort behaviour in MATLAB, GNU Octave and NumPy
Compares how the sort function in MATLAB, GNU Octave and NumPy handles descending order, index output, NaN placement and stability, compiled from each tool's official documentation read on 2026-11-12.
Period covered: 2026.
| Tool | Function | Descending order option | Index output | Missing/NaN placement | Stability |
|---|---|---|---|---|---|
| MATLAB | sort | sort(A,'descend') | [B,I] = sort(A) | Last when ascending, first when descending ('auto'); MissingPlacement first/last overrides | Stable |
| GNU Octave | sort | mode argument "descend" | [s,i] = sort(x) | NaN treated as greater than any other value and sorted to the end; descending mode not stated | Equal elements keep their original order in the index output |
| NumPy | numpy.sort | descending=True (new in 2.5) | numpy.argsort | NaN sorted to the end, also with descending=True | Default kind quicksort is not stable; stable=True selects a stable sort |
Sources
- MathWorks: sort (MATLAB documentation) (accessed 2026-11-12)
- GNU Octave manual: Rearranging Matrices (sort) (accessed 2026-11-12)
- NumPy documentation: numpy.sort (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







