フィルターのクリア

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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by