Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort MATLAB Cell Array Across multiple columns

I have data that is of the following form:

'of' 45001 23366 21859591 52876216 0 45001
'on' 40649 23226 17940625 44201973 0 40649
'my' 37976 18338 11277975 47042676 0 37976
'me' 28707 18134 6546887 36222235 0 28707

I am wondering how in MATLAB I go about sorting say column 2 from largest to smallest but keep all the other rows associated with the one that's being sorted - this is stored in a cell array also.

Any help would be appreciated.

like image 695
eWizardII Avatar asked Jan 10 '11 21:01

eWizardII


People also ask

Can you sort a cell array in Matlab?

Accepted AnswerYou can convert your cell array into a matrix using CELL2MAT, sort according to the column you choose using SORTROWS, and then convert the matrix back to a cell array using MAT2CELL. Note that there are certain limitations on the cell array for being able to use the CELL2MAT function.

How do I sort a cell array in descending order Matlab?

Accepted Answer The ability to sort a cell-array using the 'descend' option is not available with the SORT command in MATLAB. As a workaround, to create a cell array of descending order, perform the operations FLIPLR and FLIPUD on the output of SORT.

How do you sort an entire array in Matlab?

B = sort( A ) sorts the elements of A in ascending order. If A is a vector, then sort(A) sorts the vector elements. If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.

How do you sort each column of a matrix in Matlab?

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


1 Answers

Although you're dealing with a cell array, the answer actually ends up being the same as that listed for numeric arrays in the closely-related questions I linked to in my above comment: simply use the function SORTROWS. Here's how you can sort the rows of your cell array according to the values in the second column (in descending order):

sortedCellArray = sortrows(cellArray,-2);


NOTE: It should be noted that the documentation for SORTROWS doesn't appear to explicitly say that the function will work with cell array inputs, but it does have an example showing that it works for them just like it does for any other array.

like image 199
gnovice Avatar answered Sep 27 '22 18:09

gnovice