How do I sort a cell array according to a chosen column in MATLAB?

41 views (last 30 days)
I have a cell array with scalars in a particular column. I would like to sort the cell array according to this column.
For example if I have the following cell array:
a = {3 4;2 3}
How do I sort the cell array according to the first column?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This enhancement has been incorporated in Release 2008a (R2008a). For previous product releases, read below for any possible workarounds:
You 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.
The following code illustrates the solution:
a = {3 4;2 3};
a = cell2mat(a); % convert cell array to a matrix
a = sortrows(a,1); % sort according to the 1st column
a = mat2cell(a,[1 1],[1 1]) % convert matrix back into a cell array
Note that there are certain limitations on the cell array for being able to use the CELL2MAT function. Depending on your requirements, the above solution may or may not be suitable for you. You can obtain more information about these functions by typing the following commands in the Command Window.
doc cell2mat
doc mat2cell

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!