필터 지우기
필터 지우기

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