File Exchange

image thumbnail


version 3.0 (8.79 KB) by

Sort elements of several matrices corresponding to the sorting order of one matrix.

1 Download


View License

his 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);

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

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.

Comments and Ratings (2)

Chad Greene

Chad Greene (view profile)

Great suggestion Rawad. I've updated the function to allow row or column vectors.

Rawad Raidan

Hi Chad,

I had an issue using sortwith on row vectors. [ad fs gs] = sortwith(a,y,g) where a = [0 0.5 1.0 0.3278]. y and g where similar row vectors. It worked when I transposed them into column vectors.[ad fs gs] = sortwith(a',y',g').

I did not find anything in the documentation. If it is mentioned, I didn't see it. If not, a footnote could have spared me some minute pains.

It is convenient and it has helped me out. So kudos!



updated for row or column vectors.


Bug fix in descending order; extended functionality to character or cell structures.

MATLAB Release
MATLAB 8.0 (R2012b)
Tags Add Tags

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video