How to sort rows of a cell array by date/time when the other columns are different data types?

11 次查看(过去 30 天)
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?

采纳的回答

Jos (10584)
Jos (10584) 2018-9-25
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,:)

更多回答(1 个)

Peter Perkins
Peter Perkins 2018-10-1
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

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by