8

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.

1

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Duh. I checked the help to sortrows and it looked like it wasn't accepting cell arrays.
@Jonas: That's what gave me pause about calling this an exact duplicate. None of the other questions explicitly deal with cell arrays, and even the documentation doesn't seem to say anything about it!
That's why I made a new answer as well. I agree with you that it's a really close duplicate nevertheless. +1 for the better answer, though.
Docs now explicitly accept cell arrays: "Input array, specified as a column vector or matrix. The data type of A can be numeric, logical, char, cell, categorical, datetime, or duration"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.