Filter löschen
Filter löschen

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

11 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Jos (10584)
Jos (10584) am 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,:)

Weitere Antworten (1)

Peter Perkins
Peter Perkins am 1 Okt. 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

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by