Sort matrix by datenum

7 views (last 30 days)
David du Preez
David du Preez on 9 May 2017
Answered: Peter Perkins on 9 May 2017
I have a 88416 x 13 matrix. Column 1 contains the datenum values. I want to sort the matrix by column 1 keeping the corresponding values. It must be sorted from oldest to newest and keep the corresponding values

Accepted Answer

Stephen23
Stephen23 on 9 May 2017
Edited: Stephen23 on 9 May 2017
Where M is your matrix, use sortrows and its second optional argument to select the column:
sortrows(M,1)

More Answers (1)

Peter Perkins
Peter Perkins on 9 May 2017
If using MATLAB R2016b or newer, you might consider using a timetable. There are lots of benefits beyond simple sorting by time, but here's how you'd do that:
>> tt = timetable(datetime(2017,5,[1;3;2;5;4]),randn(5,1),randn(5,1),randn(5,1))
tt =
5×3 timetable
Time Var1 Var2 Var3
___________ ________ ________ _________
01-May-2017 -0.1469 -0.60006 0.96697
03-May-2017 -0.85955 -0.78089 -0.075429
02-May-2017 0.69933 -0.74781 -0.58065
05-May-2017 0.94991 0.62544 1.3161
04-May-2017 0.41305 -1.3237 1.2532
>> sortrows(tt)
ans =
5×3 timetable
Time Var1 Var2 Var3
___________ ________ ________ _________
01-May-2017 -0.1469 -0.60006 0.96697
02-May-2017 0.69933 -0.74781 -0.58065
03-May-2017 -0.85955 -0.78089 -0.075429
04-May-2017 0.41305 -1.3237 1.2532
05-May-2017 0.94991 0.62544 1.3161
Prior to R2016b, you could also use a table that contains a datetime variable. sortrows would also work on that.

Categories

Find more on Shifting and Sorting Matrices 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!