Array order is an important consideration when looping over data in MATLAB/Octave. Choosing which dimension to loop over can actually have a significant impact on computational efficiency. In this tutorial, I introduce and illustrate the concept of array order, create a simple experiment to demonstrate the effects of array order when looping, and explain how the *permute()* command in MATLAB can be used to write efficient loops every time.

All of the source code for the examples can be found in the GitHub repository.

### Array Order

When dealing with multi-dimensional or N-dimensional (ND) arrays it is important to be aware of how the data are stored in memory. This is referred to as array ordering. There are two general conventions: row-major and column-major ordering. These two different methods simply refer to which elements of the ND array area contiguous in memory, as well as, how such arrays should be linearly indexed. In column-major order, the elements of columns are contiguous in memory. and in row-major order, the elements of rows are contiguous in memory. So basically, we count elements down the columns for column-major and along the rows for row-major.

The following code snippet shows an example of a 3 x 3 matrix where each element shows what the linear index is. Similarly, you can think of the numbers in the matrix as the order of the data in memory (e.g. 1 is the first memory address, 2 is the second memory address, etc…).

We can trivially see how MATLAB stores the data by using the ‘:’ operator, which will unwrap the data. Since MATLAB is column-major, you can see that the *colMaj* matrix returns the index in proper order, but the *rowMaj* matrix returns the elements out of order.

To make this a little more clear, we can build a simple animation. The animation shows how a matrix is unwrapped using both conventions. The linear index at the bottom shows how the individual elements are actually stored in memory.

### Looping Over Data

So why does array order matter? Well, when you are looping over data, array order can actually have a significant impact on the run time. It is much more efficient to access data that is contiguous in memory. So having the knowledge of how our data is organized in memory can also help us write more computationally efficient code.

Let’s demonstrate this with a simple example. Suppose we have a collection of images that we want to operate on. The images are of size (*nX*, *nY*) pixels and we have *nI* images in our data set. There are two likely ways in which these images might be arranged in memory: [*nX*, *nY*, *nI*] or [*nI*, *nX*, *nY*]. In the first orientation, the images will be arranged contiguously in memory, while in the second orientation it will not.

To see what kind of difference array order makes, we can write the following test code. Note, the *tic()* and *toc()* functions allow us to time parts of our code execution. If you are not familiar with this functions, *tic()* essentially starts a timer and *toc()* records how much time has elapsed since you started the timer. You can find more documentation in the MATLAB help.

To illustrate the effects of array order, the code was run with *nX* = *nY* = 128 and *nI* taking on values of 1,000, 10,000, and 50,000. The brave and curious are encouraged to download the source code and try out more interesting combinations!

Starting with just 1,000 images, we can see that the array order doesn’t seem to have a big impact, however, there is still about a 10% increase in run time.

Increasing the number of images to 10,000, we start to see an actual difference in run times. There is 2.4 factor increase in run time when the images are not stored contiguously in memory.

Further increasing the number of images to 50,000, we continue to see larger increase in the run time. There is now a factor 8 increase in the run time!

It is important to note that this was a simple example with a single loop and only three dimensions. This effect can actually be much worse for arrays with more dimensions or when we are nesting multiple loops. Sometimes it is worthwhile to add some *tic() / toc() *calls to your code or to run Profiler to where you might want to make some updates to your code.

### Permute() in MATLAB

MATLAB includes a function called *permute()*, which is a generalization of the transpose function but for ND arrays. *Permute()* takes in an ND-array and the desired array order and then returns the rearranged data. The syntax looks this: *newArray = permute( oldArray, [oldDim1, oldDim2, oldIm3, etc…] *). In this syntax the variables *oldDim#* represent array order index of the old array and the position in the function input represent the new array order position.

For example, suppose we have an ND-array, *A*, of shape [200, 450, 120, 680], and that we called the permute() function as such: *B* = permute( A, [3, 1, 4, 2]). The resulting shape of array *B* would be [120, 200, 680, 450]. Here we have moved dimension 3 to dimension 1, dimension 1 to dimension 2, dimension 4 to dimension 3, and dimension 2 to dimension 4.

Using the *permute()* function, we can rearrange any ND-array based on what dimension we want to loop over. Returning to our previous image example, we can take our array *imageData* of shape [*nI, nX, nY*], and rearrange this to an array of shape [*nI, nX, nY*] by using the following command.

This would now allow us to loop over the last dimension, which we just showed to be more computational efficient. Adding this simple line to our previous example, we can re-run our test. The updated code will look as follows.

Running this experiment with *nI* = 50,000, results in the following output.

Using the *permute()* command has significantly reduced our looping time. There is, of course, a small overhead for using the permute function, but in almost all practical cases it is best to include it. As I mentioned previously, this is especially true with high-dimensional arrays and when we are nesting multiple loops.

### Summary

In this tutorial we covered the importance of array order when looping over ND-arrays in MATLAB/Octave. Using some simple MATLAB code, we demonstrated the benefit of looping over data that is contiguous in memory. We further showed that the *permute()* command allows us to rearrange the array dimensions before looping so we can always ensure that we are looping efficiently.

Here are a few points to remember:

- Data are arranged in column-major order in MATLAB
- We should always loop over the outermost dimensions to make our loops as efficient as possible.
*Permute()*can be used before (and after) any loop to ensure that we loop over ND-arrays efficiently.- For nested loops, the innermost loop should loop over the outermost dimension.

Happy coding!

coding tipsMATLABOctave

Sours: https://thinkdata.science/?p=239MATLAB Function Reference |

Sort array elements in ascending or descending order

**Syntax**

- B = sort(A) B = sort(A,dim) B = sort(...,mode) [B,IX] = sort(...)

**Description**

sorts the elements along different dimensions of an array, and arranges those elements in ascending order.

If A is a ... | sort(A) ... |

Vector | Sorts the elements of . |

Matrix | Sorts each column of . |

Multidimensional array | Sorts along the first non-singleton dimension, and returns an array of sorted vectors. |

Cell array of strings | Sorts the strings in ASCII dictionary order. |

Integer, real, logical, and character arrays are permitted. Floating-point arrays can be complex. For elements of A with identical values, the order of these elements is preserved in the sorted list. When is complex, the elements are sorted by magnitude, i.e., , and where magnitudes are equal, further sorted by phase angle, i.e., , on the interval . If includes any elements, places these at the high end.

sorts the elements along the dimension of specified by a scalar .

sorts the elements in the specified direction, depending on the value of .

Ascending order (default) | |

Descending order |

also returns an array of indices , where. If is a vector, . If is an -by- matrix, then each column of is a permutation vector of the corresponding column of , such that

- for j = 1:n B(:,j) = A(IX(:,j),j); end

If has repeated elements of equal value, the returned indices preserve the original ordering.

**Sorting Complex Entries**

If has complex entries and , orders them according to the following rule: appears before in if either of the following hold:

- and

where

For example,

- v = [1 -1 i -i]; angle(v) ans = 0 3.1416 1.5708 -1.5708 sort(v) ans = 0 - 1.0000i 1.0000 0 + 1.0000i -1.0000

Note uses a different rule for ordering complex numbers than do and , or the relational operators < and >. See the Relational Operators reference page for more information. |

**Examples**

**Example 1.** This example sorts a matrix in each dimension, and then sorts it a third time, requesting an array of indices for the sorted result.

- A = [ 3 7 5 0 4 2 ]; sort(A,1) ans = 0 4 2 3 7 5 sort(A,2) ans = 3 5 7 0 2 4 [B,IX] = sort(A,2) B = 3 5 7 0 2 4 IX = 1 3 2 1 3 2

**Example 2.** This example sorts each column of a matrix in descending order.

- A = [ 3 7 5 6 8 3 0 4 2 ]; sort(A,1,'descend') ans = 6 8 5 3 7 3 0 4 2

This is equivalent to

- sort(A,'descend') ans = 6 8 5 3 7 3 0 4 2

**See Also**

, , , , ,

smooth3 | sortrows |

© 1994-2005 The MathWorks, Inc.

MATLAB Function Reference |

Sort elements in ascending order

**Syntax**

- B = sort(A) B = sort(A,dim) [B,INDEX] = sort(A,...)

**Description**

sorts the elements along different dimensions of an array, and arranges those elements in ascending order.

If A is a ... | sort(A) ... |

Vector | Sorts the elements of in ascending order. |

Matrix | Sorts each column of in ascending order. |

Multidimensional array | Sorts along the first non-singleton dimension, and returns an array of sorted vectors. |

Cell array of strings | Sorts the strings in ASCII dictionary order. |

Real, complex, and string elements are permitted. For elements of A with identical values, the order of these elements is preserved in the sorted list. When is complex, the elements are sorted by magnitude, i.e., , and where magnitudes are equal, further sorted by phase angle, i.e., , on the interval . If includes any elements, places these at the end.

sorts the elements along the dimension of specified by a scalar . If is a vector, works iteratively on the specified dimensions. Thus, is equivalent to .

also returns an array of indices , where. If is a vector, . If is an -by- matrix, then each column of is a permutation vector of the corresponding column of , such that

- for j = 1:n B(:,j) = A(IX(:,j),j); end

If has repeated elements of equal value, the returned indices preserve the original ordering.

**Examples**

This example sorts a matrix in each dimension, and then sorts it a third time, requesting an array of indices for the sorted result.

- A = [ 3 7 5 0 4 2 ]; sort(A,1) ans = 0 4 2 3 7 5 sort(A,2) ans = 3 5 7 0 2 4 [B,IX] = sort(A,2) B = 3 5 7 0 2 4 IX = 1 3 2 1 3 2

**See Also**

, , , ,

smooth3 | sortrows |

## sortrows

Main Content

### Syntax

### Description

example

sorts the rows of a matrix in ascending order based on the elements in the first column. When the first column contains repeated elements, sorts according to the values in the next column and repeats this behavior for succeeding equal values.

example

sorts based on the columns specified in the vector . For example, sorts the rows of in ascending order based on the elements in the fourth column. first sorts the rows of based on the elements in the fourth column, then based on the elements in the sixth column to break ties.

example

sorts the rows of in the order specified by for any of the previous syntaxes. can be (default) for ascending order or for descending order. can also be a cell array whose elements are and , where each element corresponds to a column that operates on. For example, sorts the rows of in ascending order based on the fourth column, then in descending order based on the sixth column to break ties.

example

specifies additional parameters for sorting rows. For example, sorts the elements of by magnitude.

example

also returns an index vector that describes the rearrangement of rows such that .

example

sorts the rows of a table in ascending order based on the values in the first variable. If elements in the first variable are repeated, then sorts by the elements in the second variable, and so on.

If is a timetable, then sorts the rows of in ascending order based on its row times. Row times of a timetable label the rows along the first dimension of the timetable.

example

sorts a table based on its row names. Row names of a table label the rows along the first dimension of the table. If does not have row names, that is, if is empty, then returns .

This syntax is not supported when is a timetable.

example

sorts by row labels along the first dimension.

If is a table, then row labels are row names.

If is a timetable, then row labels are row times.

example

sorts a table by the elements in the variables specified by . For example, first sorts the rows of based on the elements in , then by the elements in .

If is a table and it has row names, then can include the row names.

If is a timetable, then can include the row times.

example

sorts in the order specified by for any of the previous table syntaxes. can be or , which is applied to all specified variables, row names, or row times that operates on. can also be a cell array whose elements are and , where each element corresponds to the specified variables, row names, or row times being sorted on.

example

specifies additional parameters for sorting rows of a table or timetable. For example, sorts based on the elements in , ordering missing elements such as at the beginning of the table.

example

also returns an index vector such that .

### Examples

collapse all

### Sort Rows of Matrix

Create a matrix and sort its rows in ascending order based on the elements in the first column. When the first column contains repeated elements, looks to the elements in the second column to break the tie. For repeated elements in the second column, looks to the third column, and so on.

*6×7*95 27 95 79 67 70 69 95 7 48 95 75 3 31 95 7 48 65 74 27 95 95 7 14 3 39 4 3 76 15 42 84 65 9 43 76 97 91 93 17 82 38

*6×7*76 15 42 84 65 9 43 76 97 91 93 17 82 38 95 7 14 3 39 4 3 95 7 48 65 74 27 95 95 7 48 95 75 3 31 95 27 95 79 67 70 69

Sort the rows of based on the values in the second column. When the specified column has repeated elements, the corresponding rows maintain their original order.

*6×7*95 7 48 95 75 3 31 95 7 48 65 74 27 95 95 7 14 3 39 4 3 76 15 42 84 65 9 43 95 27 95 79 67 70 69 76 97 91 93 17 82 38

Sort the rows of based on the elements in the first column, and look to the seventh column to break any ties.

*6×7*76 97 91 93 17 82 38 76 15 42 84 65 9 43 95 7 14 3 39 4 3 95 7 48 95 75 3 31 95 27 95 79 67 70 69 95 7 48 65 74 27 95

Sort the rows of in descending order based on the elements in the fourth column, and display the output vector to see how the rows were rearranged.

*6×7*95 7 48 95 75 3 31 76 97 91 93 17 82 38 76 15 42 84 65 9 43 95 27 95 79 67 70 69 95 7 48 65 74 27 95 95 7 14 3 39 4 3

### Complex Matrix

Create a matrix containing complex numbers, and sort the rows of the matrix in ascending order based on the elements in the first column. Since the magnitudes of and are equal, computes their angles to break the tie.

*3×3 complex*1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i 2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i

*3×3 complex*2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i 1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i

Use the option to sort the rows of by their real part. Since and have equal real parts, uses the imaginary part to break the tie.

*3×3 complex*1.0000 + 2.0000i 3.0000 + 1.0000i 0.0000 + 1.0000i 2.0000 + 1.0000i 4.0000 + 0.0000i 3.0000 + 3.0000i 2.0000 +10.0000i 0.0000 + 6.0000i 2.0000 + 5.0000i

### Sort Rows of Cell Array

Create a 6-by-2 cell array of character vectors, and sort its rows. The result is an alphabetized list sorted by both country and name.

*6x2 cell*{'Germany'} {'Lukas' } {'USA' } {'William'} {'USA' } {'Andrew' } {'Germany'} {'Andreas'} {'USA' } {'Olivia' } {'Germany'} {'Julia' }

*6x2 cell*{'Germany'} {'Andreas'} {'Germany'} {'Julia' } {'Germany'} {'Lukas' } {'USA' } {'Andrew' } {'USA' } {'Olivia' } {'USA' } {'William'}

Sort the countries first, then sort the names in descending order.

*6x2 cell*{'Germany'} {'Lukas' } {'Germany'} {'Julia' } {'Germany'} {'Andreas'} {'USA' } {'William'} {'USA' } {'Olivia' } {'USA' } {'Andrew' }

### Sort Rows of Table

Sort the rows of a table by variable values.

Create a table with four variables listing patient information for five people.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Smith 38 71 176 124 93 Johnson 43 69 163 109 77 Williams 38 64 131 125 83 Jones 40 67 133 117 75 Brown 49 64 119 122 80

Sort the rows of the table. The function sorts the rows in ascending order first by the variable , and then by the variable to break the tie between the two rows with equal ages.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Williams 38 64 131 125 83 Smith 38 71 176 124 93 Jones 40 67 133 117 75 Johnson 43 69 163 109 77 Brown 49 64 119 122 80

### Sort Rows of Table by Row Names

Create a table with four variables listing patient information for five people.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Smith 38 71 176 124 93 Johnson 43 69 163 109 77 Williams 38 64 131 125 83 Jones 40 67 133 117 75 Brown 49 64 119 122 80

Sort the rows of the table in ascending order based on the row names, and return the index vector that describes how the rows were rearranged.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Brown 49 64 119 122 80 Johnson 43 69 163 109 77 Jones 40 67 133 117 75 Smith 38 71 176 124 93 Williams 38 64 131 125 83

### Sort Rows of Table by Variables

Create a table with four variables listing patient information for five people.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Sweet 38 71 176 124 93 Jacobson 43 69 163 109 77 Wang 38 64 131 125 83 Joiner 40 67 133 117 75 Berger 49 64 119 122 80

Sort the rows of the table in ascending order by , and then in descending order by .

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Wang 38 64 131 125 83 Berger 49 64 119 122 80 Joiner 40 67 133 117 75 Jacobson 43 69 163 109 77 Sweet 38 71 176 124 93

### Table with Missing Elements

Create a table with four variables listing patient information for five people. The variable contains missing values.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Sweet 38 71 176 124 93 Jacobson 43 69 NaN 109 77 Wang 38 64 131 125 83 Joiner 40 67 133 117 75 Berger 49 64 NaN 122 80

Sort the rows of the table in ascending order by , placing the rows containing first.

*5×4 table*Age Height Weight BloodPressure ___ ______ ______ _____________ Jacobson 43 69 NaN 109 77 Berger 49 64 NaN 122 80 Wang 38 64 131 125 83 Joiner 40 67 133 117 75 Sweet 38 71 176 124 93

### Sort Rows of Timetable

Create a timetable, and sort the rows by row times.

*5×2 timetable*TimeDuration Var1 Var2 ____________ ____ ____ 1 hr 97.9 119 2 hr 97.5 111 3 hr 98 120 5 hr 98.1 117 6 hr 101 118

### Input Arguments

collapse all

### — Input array

column vector | matrix

Input array, specified as a column vector or matrix.

**Data Types: ** | | | | | | | | | | | | | | | | **Complex Number Support: **Yes

### — Column sorting vector

nonzero integer scalar | vector of nonzero integers

Column sorting vector, specified as a nonzero integer scalar or a vector of nonzero integers. Each specified integer value indicates a column to sort by. Negative integers indicate that the sort order is descending.

### — Sorting direction

character vector | cell array of character vectors

Sorting direction, specified as a character vector or cell array of character vectors containing (default) or . If is a cell array of character vectors, then the number of entries must match the number of columns or variables being sorted on.

If the argument and the argument are specified together, then sorts according to , ignoring the signs of the elements in .

**Data Types: ** | |

### — Input table

table | timetable

Input table, specified as a table or a timetable. Each variable in must be a valid input to or .

**Data Types:** |

### — Name of first dimension of input table or timetable

character vector

Name of the first dimension of the input table or timetable, specified as a character vector.

If is a table with row names, then is the name of the first dimension of the table. By default, the name of the first dimension is . Dimension names are a property of tables. You can access the dimension names of using .

If is a timetable, then is the name of the vector of row times. You can specify its name when you create a timetable, such as or . You can also access the dimension names using .

**Example: **If a table has row names, and you changed the name of the first dimension using , then sorts the table by row name.

**Example: **If a timetable has a time vector named , then sorts the timetable on the dates and times that contains.

**Data Types: **

### — Sorting variables

scalar integer | vector of integers | variable name | cell array of variable names | logical vector

Sorting variables, specified as a scalar integer, a vector of integers, a variable name, a cell array of variable names, or a logical vector. indicates the table variables to sort by.

If an element of is a positive integer, then sorts the corresponding variable in in ascending order. If an element of is a negative integer, then sorts the corresponding variable in in descending order.

**Example: ** sorts the rows of in ascending order, first by the variable , then by the variable to break ties.

**Example: ** sorts by the first variable of in ascending order, then sorts by the fourth variable to break ties.

**Example: ** sorts the row times of timetable in ascending order first, then sorts by the table variable to break ties.

**Data Types: ** | | | | |

### Name-Value Arguments

Specify optional comma-separated pairs of arguments. is the argument name and is the corresponding value. must appear inside quotes. You can specify several name and value pair arguments in any order as .

**Example:**

### — Placement of missing values

(default) | |

Placement of missing values (, , , and ) specified as the comma-separated pair consisting of and one of the following:

— Missing elements are placed last for ascending order and first for descending order.

— Missing elements are placed first.

— Missing elements are placed last.

### — Element comparison method

(default) | |

Element comparison method, specified as the comma-separated pair consisting of and one of the following:

— Sort rows of by when is real, and sort by when is complex.

— Sort rows of by when is real or complex. If a column of has elements with equal real parts, then use to break ties.

— Sort rows of by when is real or complex. If a column of has elements with equal magnitude, then use in the interval (-π,π] to break ties.

### Output Arguments

collapse all

### — Sorted array

vector | matrix | multidimensional array

Sorted array, returned as a vector, matrix, or multidimensional array. is the same size as .

**Data Types: ** | | | | | | | | | | | | | | | |

### — Sorted table

table | timetable

Sorted table, returned as a table or timetable with the same variables as .

**Data Types:** |

### — Sort index

index vector

Sort index, returned as an index vector. The sort index describes the rearrangement of the rows in the input such that .

**Data Types: **

### Extended Capabilities

### Tall Arrays

Calculate with arrays that have more rows than fit in memory.

This function supports tall arrays with the limitations:

Sorting by row names is not supported.

For more information, see Tall Arrays.

### C/C++ Code Generation

Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

The first input argument must not be a cell array.

If is complex with all zero imaginary parts, then MATLAB

^{®}might convert to before calling . In this case, MATLAB sorts the rows of by , but the generated code sorts the rows of by . To make the generated code match MATLAB, use or . See Code Generation for Complex Data with Zero-Valued Imaginary Parts (MATLAB Coder).If is a table or timetable, then the input argument must be constant.

If is a table or timetable, and it has a variable that is a cell array of character vectors with multiple columns, then you cannot sort using the values in that variable.

### GPU Code Generation

Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.

Usage notes and limitations:

The first input argument must not be a cell array.

If is complex with all zero imaginary parts, then MATLAB might convert to before calling . In this case, MATLAB sorts the rows of by , but the generated code sorts the rows of by . To make the generated code match MATLAB, use or .

### Thread-Based Environment

Run code in the background using MATLAB® or accelerate code with Parallel Computing Toolbox™ .

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™.

Usage notes and limitations:

Sorting cell arrays is not supported.

Sparse inputs are not supported.

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:

Sorting cell arrays is not supported.

For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

**Introduced before R2006a**

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

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: .

Select web siteYou can also select a web site from the following list:

### How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

## Order array matlab

## sort

Main Content

### Description

example

sorts the elements of in ascending order.

If is a vector, then sorts the vector elements.

If is a matrix, then treats the columns of as vectors and sorts each column.

If is a multidimensional array, then operates along the first array dimension whose size does not equal 1, treating the elements as vectors.

example

returns the sorted elements of along dimension . For example, if is a matrix, then sorts the elements of each row.

example

returns sorted elements of in the order specified by using any of the previous syntaxes. indicates ascending order (the default) and indicates descending order.

example

specifies additional parameters for sorting. For example, sorts the elements of by magnitude.

example

also returns a collection of index vectors for any of the previous syntaxes. is the same size as and describes the arrangement of the elements of into along the sorted dimension. For example, if is a vector, then .

### Examples

collapse all

### Sort Vector in Ascending Order

Create a row vector and sort its elements in ascending order.

*1×9*-10 -7 0 2 3 4 5 8 9

### Sort Matrix Rows in Ascending Order

Create a matrix and sort each of its rows in ascending order.

*3×3*3 6 5 7 -2 4 1 0 -9

*3×3*3 5 6 -2 4 7 -9 0 1

### Sort Matrix Columns in Descending Order

Create a matrix and sort its columns in descending order.

*4×4*10 -12 4 8 6 -9 8 0 2 3 11 -2 1 1 9 3

*4×4*10 3 11 8 6 1 9 3 2 -9 8 0 1 -12 4 -2

### Sort String Array

Starting in R2017a, you can create string arrays using double quotes, and sort them using the function. Sort strings in each column of a string array according to Unicode® dictionary order.

*3x2 string*"Jones" "Adams" "Petrov" "Burns" "Santos" "Morita"

Sort the strings in each row.

*3x2 string*"Burns" "Santos" "Jones" "Morita" "Adams" "Petrov"

### Sort and Index Array

Create an array of values and sort them in ascending order, that is, from the earliest to the latest calendar date.

*3x1 datetime*2012-12-22 2063-04-05 1992-01-12

*3x1 datetime*1992-01-12 2012-12-22 2063-04-05

lists the sorted dates and contains the corresponding indices of .

Access the sorted elements from the original array directly by using the index array .

*3x1 datetime*1992-01-12 2012-12-22 2063-04-05

### Sort Vectors in Same Order

Create two row vectors that contain related data in the corresponding elements.

First sort the vector , then sort the vector in the same order as .

*1×6*1 2 3 4 5 6

*1x6 string*"red" "orange" "yellow" "green" "blue" "purple"

### Sort 3-D Array

Create a 2-by-2-by-2 array and sort its elements in ascending order along the third dimension.

Use , the column representation of , to sort all of the elements of .

*8×1*-1 0 1 2 3 6 9 12

### Complex Vector

Sort the elements of a complex vector by their real parts. By default, the function sorts complex values by their magnitude, and breaks ties using phase angles. Specify the value of as to instead sort complex values by their real parts. For elements with equal real parts, breaks the tie based on their imaginary parts.

*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

### — Input array

vector | matrix | multidimensional array

Input array, specified as a vector, matrix, or multidimensional array.

If is a scalar, then returns .

If is complex, then by default, sorts the elements by magnitude. If more than one element has equal magnitude, then the elements are sorted by phase angle on the interval (−π, π].

If is a cell array of character vectors or a string array, then sorts the elements according to the code order for the UTF-16 character encoding scheme. The sort is case-sensitive. For more information on sorting character and string arrays, see Sort Order for Character and String Arrays.

If is a string array, then reorders the elements of the array, but does not reorder characters within the strings.

If is a categorical array, then the sorting order is based on the category order returned by .

**Data Types: ** | | | | | | | | | | | | | | | | **Complex Number Support: **Yes

### — Dimension to operate along

positive integer scalar

Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the default is the first array dimension whose size does not equal 1.

Consider a matrix . sorts the elements in the columns of .

sorts the elements in the rows of .

returns if is greater than . is not supported when is a cell array, that is, only operates along the first array dimension whose size does not equal 1.

**Data Types: ** | | | | | | | | |

### — Sorting direction

(default) |

Sorting direction, specified as or . is not supported when is a cell array, that is, only sorts in ascending order.

### Name-Value Arguments

Specify optional comma-separated pairs of arguments. is the argument name and is the corresponding value. must appear inside quotes. You can specify several name and value pair arguments in any order as .

**Example:**

### — Placement of missing values

(default) | |

Placement of missing values (, , , and ) specified as the comma-separated pair consisting of and one of the following:

— Missing elements are placed last for ascending order and first for descending order.

— Missing elements are placed first.

— Missing elements are placed last.

### — Element comparison method

(default) | |

Element comparison method, specified as the comma-separated pair consisting of and one of the following:

— Sort by when is real, and sort by when is complex.

— Sort by when is real or complex. If has elements with equal real parts, then use to break ties.

— Sort by when is real or complex. If has elements with equal magnitude, then use in the interval (-π,π] to break ties.

### Output Arguments

collapse all

### — Sorted array

vector | matrix | multidimensional array

Sorted array, returned as a vector, matrix, or multidimensional array. is the same size and type as .

**Data Types: ** | | | | | | | | | | | | | | | |

### — Sort index

vector | matrix | multidimensional array

Sort index, returned as a vector, matrix, or multidimensional array. is the same size as . The index vectors are oriented along the same dimension that operates on. For example, if is a 2-by-3 matrix, then sorts the elements in each row of . The output is a collection of 1-by-3 row index vectors describing the rearrangement of each row of .

When the input contains repeated values, the sort index preserves the original order in the input, regardless of sort direction. For example, if , then returns the sort index and returns the sort index .

### More About

collapse all

### Sort Order for Character and String Arrays

MATLAB^{®} stores characters as Unicode^{®} using the UTF-16 character encoding scheme. Character and string arrays are sorted according to the UTF-16 code point order. For the characters that are also the ASCII characters, this order means that uppercase letters come before lowercase letters. Digits and some punctuation also come before letters.

### Tips

The function provides additional flexibility for subsorting over multiple columns of matrix or table inputs.

The function and the relational operators 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 .

Sorting the tall dimension, as in , 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:

### Thread-Based Environment

Run code in the background using MATLAB® or accelerate code with Parallel Computing Toolbox™ .

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™.

This function fully supports GPU arrays. 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™.

This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).

**Introduced before R2006a**

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

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: .

Select web siteYou can also select a web site from the following list:

### How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

Duty, they say he is connected with Polish intelligence. So he will no longer threaten you, Alexey Ivanovich. I think that by morning he will sign about talk about connections with both defensive and ciguranza. But the box with jewelry, the bribe found in his possession has not yet been canceled.

### Similar news:

- Car rentals hayward
- Real snake eyes sword
- Paper holder organizer
- Top 50 instrumental songs
- Dodge viper convertible
- Best index funds
- 2001 toyota corolla
- Aim math u see

Then they sell them to some slave owners, they resell them to a wild African tribe. In general, the whole dream is with you and they just do that f ut. Including between the boobs, in the armpit, in the popliteal fold, in the auricle. And for some reason you are sweet all night, you are finished.

Interpretation of the twelfth dream.

**1696**1697 1698