Sorting rows in MATLAB is a common task when you need to organize table data or matrix observations by one or more variables. The sortrows function lets you specify column indices or names to control the sort order and direction.
Below you will find practical details, syntax options, and examples that help you use sortrows reliably in data processing scripts and functions.
| Function | Primary Use | Typical Input | Key Options |
|---|---|---|---|
sortrows |
Sort rows of a matrix or table | Matrix, table, or timetable | Direction, missing placement, sort indices |
sort |
Sort elements within a dimension | Vector, matrix, or array | Dimension, comparison method |
rows (old syntax) |
Legacy notation for row sorting | Matrix expressions | Limited flexibility compared to sortrows |
stable vs quicksort |
Control algorithm behavior | Name-value arguments | Preserve order of equal elements or optimize speed |
Basic Syntax and Output Behavior
Default Row Sorting
Using sortrows without extra arguments sorts by the first column in ascending order and automatically breaks ties using the next columns. This behavior works consistently for numeric, datetime, string, and categorical data.
Specifying Columns and Direction
You can choose which columns to sort by and whether each column should be ascending or descending. This is useful when the primary key is not the first column or when you need descending priority for certain variables.
Sorting Tables and Timetables by Variable Names
Using Variable Names Instead of Indices
When working with tables, it is often clearer to refer to variable names instead of column indices. sortrows accepts a string or character vector with the variable name, which makes scripts easier to read and maintain.
Multiple Variable Sorting
Sorting by several variables in a specific priority order is straightforward. You provide a cell array of names or a comma-separated list and pair each name with a direction. This approach is common for preparing reports or ensuring deterministic row ordering before merging datasets.
Handling Missing Data and Sorting Direction
Placement of Missing Values
MATLAB lets you control where NaN, NaT, missing, or blank strings appear in the sorted result. You can place missing values first or last on a per-column basis, which is important for downstream logic that depends on row positions.
Stable Sorting and Algorithm Choice
Choosing between a stable sort and a faster quicksort-style implementation affects performance and row order for equal keys. A stable sort preserves the original order among equal elements, while quicksort may be faster on large numeric matrices with few repeated values.
Performance Tips and Input Types
Preallocating and Index Reuse
For repeated operations on large tables, pre-sorting keys into numeric indices can reduce overhead. You can sort once, store the permutation, and apply it to multiple variables that share the same row structure.
Supported Data Types
sortrows works with numeric matrices, tables, and timetables. It supports complex numbers by sorting first by real part and then by imaginary part. For tables, mixed types are allowed as long as the sort columns have compatible comparison rules.
Best Practices for Reliable Row Sorting
- Prefer variable names over column indices when working with tables to keep code readable.
- Explicitly specify direction for each column to avoid unexpected ascending defaults.
- Control missing value placement to ensure downstream logic does not misalign rows.
- Use a stable sort when row order among equal keys must be preserved for reproducibility.
- Validate key columns for consistent data types before calling
sortrowson large datasets.
FAQ
Reader questions
How does sortrows handle ties when multiple columns are specified?
When ties occur in the primary sorting column, sortrows uses the next specified column to determine row order, continuing through the list until all sort keys are exhausted. This produces a deterministic and reproducible row sequence.
Can I sort in descending order for only some columns?
Yes, you can mix ascending and descending directions by providing a cell array of 'ascend' and 'descend' values aligned with each sorting column. This allows you to prioritize one variable descending while secondary variables remain ascending.
What happens if I include a non-sortable column in a table?
If a table contains variables that cannot be compared, such as cell arrays or objects without defined ordering, specifying those variables in sortrows will produce an error. You should select only numeric, datetime, string, categorical, or otherwise orderable variables.
Is the output always a new table, or can I sort in place?
sortrows returns a new table or matrix with reordered rows; it does not modify the input in place. To update a variable, you must assign the result back to the same or a new variable name in your workspace.