Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

sorting table by date with specific date format- matlab

i got this table that i want to sort the rows by the date in one of the columns, the table basicly looks like this:

label1     01/12/2020     500     Type2;
label1     26/11/2020     553     Type1;
label2     01/01/2021     951     Type3;
label2     18/12/2019     658     Type3;
label1     01/12/2020     500     Type2;

when i use sortrows it sorts the table by the format MM-dd-yyyy though i need to change it to dd-MM-yyyy so the table will look like this in the end :

label2     18/12/2019     658     Type3;
label1     26/11/2020     553     Type1;
label1     01/12/2020     500     Type2;
label1     01/12/2020     500     Type2;
label2     01/01/2021     951     Type3;

please help solve this

question from:https://stackoverflow.com/questions/65650538/sorting-table-by-date-with-specific-date-format-matlab

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your best bet here is to convert the timestamp data into datetime. The datetime constructor can automatically work out the format in this case, so here's all you need:

% Create table
t = table(["label1"; "label1"; "label2"], ...
    ["01/12/2020"; "26/11/2020"; "01/01/2021"], ...
    [500; 553; 951], ...
    ["Type2"; "Type1"; "Type3"]);

% Convert Var2 into datetime format
t.Var2 = datetime(t.Var2);

% Now use sortrows
sortrows(t, 2)

This gives the result

  3×4 table

      Var1         Var2        Var3     Var4  
    ________    ___________    ____    _______

    "label1"    26-Nov-2020    553     "Type1"
    "label1"    01-Dec-2020    500     "Type2"
    "label2"    01-Jan-2021    951     "Type3"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...