MATLAB Examples

# sortwith

This function sorts input matrix A and corresponding matrices using sortrows. Output matrices are sorted such that the first output is a sorted version of A, and all other outputs are sorted in the same order as A. For example,

[B1,B2,...,Bn] = sortwith(A1,A2,...,An) is functionally equivalent to

```[B1,ind] = sortrows(A1);
B2 = A2(ind);
.
.
.
Bn = An(ind);```

Input matrices can be numeric, character, cell or structures.

## Syntax

```B = sortwith(A)
[B1,B2,...,Bn] = sortwith(A1,A2,...,An)
sortwith(...,'descend')```

## Description

B = sortwith(A) sorts the rows of A in ascending order. Argument A must be either a matrix or a column vector. This usage is exactly equivalent to B = sortrows(A).

[B1,B2,...,Bn] = sortwith(A1,A2,...,An) sorts matrices A1 through An corresponding to the order in which A1 is sorted.

sortwith(...,'descend') sorts the elements in descending order.

## Examples

Create A and sort it. To create A, we use the randi function to generate a 7 by 1 array of random numbers that do not exceed 10:

```A = randi(10,7,1) B = sortwith(A) ```
```A = 5 1 7 3 2 3 6 B = 1 2 3 3 5 6 7 ```

We can also sort in descending order:

```Bd = sortwith(A,'descend') ```
```Bd = 7 6 5 3 3 2 1 ```

Sometimes you have a lot of data that you want to sort referenced to the sorting order of A1. sortwith was designed to do this all in one fell swoop:

```A1 = randi(10,7,1); A2 = randi(10,7,1) + 20; A3 = randi(10,7,1) + 30; A4 = randi(10,7,1) + 40; [B1,B2,B3,B4] = sortwith(A1,A2,A3,A4) ```
```B1 = 1 2 2 4 5 7 9 B2 = 21 22 24 21 23 30 23 B3 = 38 33 39 31 36 33 39 B4 = 50 46 47 50 41 43 41 ```

And this can be done in descending order:

```[B1d,B2d,B3d,B4d] = sortwith(A1,A2,A3,A4,'descend'); ```

Inputs do not need to have the same number of columns, but they must have the same number of rows:

```A5 = randi(10,7,1); A6 = randi(10,7,3); A7 = randi(10,7,2); [B5,B6,B7] = sortwith(A5,A6,A7) ```
```B5 = 4 4 7 8 9 10 10 B6 = 9 4 2 7 5 10 8 6 5 10 10 6 8 7 5 5 6 5 5 1 5 B7 = 5 2 8 4 10 8 3 4 6 4 7 7 8 2 ```

## Author Info

These functions were written by Chad A. Greene of the University of Texas at Austin's Institute for Geophysics (UTIG) August 11, 2014. Updated August 18, 2014 with of some very helpful suggestions by Stephen Cobeldick. Thanks Stephen.