Trup
Trup

Reputation: 1655

Sorting a cell array

I want to sort the rows according to their second entries, i.e. by second column. Each entry of the second column is an array chars(representing a time stamp). There also might be missing values, i.e. the entry in the second column can be []. How do I do this?

Upvotes: 2

Views: 10340

Answers (2)

gnovice
gnovice

Reputation: 125874

I would first convert the time stamps from strings to numeric values using the function DATENUM. Then you will want to replace the contents of the empty cells with a place holder, like NaN. The you can use the function SORTROWS to sort based on the second column. Here is an example:

>> mat = {1 '1/1/10' 3; 4 [] 6; 7 '1/1/09' 9}  %# Sample cell array

mat = 

    [1]    '1/1/10'    [3]
    [4]          []    [6]
    [7]    '1/1/09'    [9]

>> validIndex = ~cellfun('isempty',mat(:,2));  %# Find non-empty indices
>> mat(validIndex,2) = num2cell(datenum(mat(validIndex,2)));  %# Convert dates
>> mat(~validIndex,2) = {NaN};  %# Replace empty cells with NaN
>> mat = sortrows(mat,2)  %# Sort based on the second column

mat = 

    [7]    [733774]    [9]
    [1]    [734139]    [3]
    [4]    [   NaN]    [6]

The NaN values will be sorted to the bottom in this case.

Upvotes: 0

A. K.
A. K.

Reputation: 38264

you need to use the sortrows() function if the matrix you wanted to sort is A then use

sorted_matrix = sortrows(A,2);

http://www.mathworks.com/help/techdoc/ref/sortrows.html

Upvotes: 5

Related Questions