How to sort rows of a cell array by date/time when the other columns are different data types?
6 views (last 30 days)
Show older comments
Samantha Wallace
on 25 Sep 2018
Commented: Jos (10584)
on 2 Oct 2018
How to sort rows of a cell array by date/time when the other columns are different data types? In the cell array the first column is notes about the row, the second column is the date and time, the third and fourth are numbers. I would like to sort the entire cell array based on the date and time in ascending order. Is there a way to do this?
0 Comments
Accepted Answer
Jos (10584)
on 25 Sep 2018
I assume your date time are stored in strings. Here is a simple approach
% some data
C = {'A' datestr(now) 1 11 ; 'B' datestr(now-100) 2 22 ; 'C' datestr(now+100) 3 33}
% sort on dates, keep the sorting indices
[~,ix] = sort(datenum(C(:,2)))
% sort cell rows accordingly
OutC = C(ix,:)
More Answers (1)
Peter Perkins
on 1 Oct 2018
Samantha, this sounds like you could be using a timetable, rather than a cell array. You will likely find things easier to work with that way. Also, unless you are using a pretty old version of MATLAB, you should try using datetime rather than datenum/datestr/datevec. For example:
>> Notes = ["a"; "bb"; "ccc"]; X = [1;2;3]; Y = [4;5;6];
>> tt = timetable(Notes,X,Y,'RowTimes',datetime(2018,10,1,0,0,0)+hours(rand(3,1)))
tt =
3×3 timetable
Time Notes X Y
____________________ _____ _ _
01-Oct-2018 00:16:16 "a" 1 4
01-Oct-2018 00:01:16 "bb" 2 5
01-Oct-2018 00:29:55 "ccc" 3 6
>> sortrows(tt)
ans =
3×3 timetable
Time Notes X Y
____________________ _____ _ _
01-Oct-2018 00:01:16 "bb" 2 5
01-Oct-2018 00:16:16 "a" 1 4
01-Oct-2018 00:29:55 "ccc" 3 6
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!