matlabmatlab-table

Create table with mixed data types from arrays


I would like to compose several arrays into one table. Since they have different data types, it seems not very straightforward. Consider this simple MWE:

daysTotal       = 2;
hoursTotal      = daysTotal*24;
timeStepHours   = 1/4;
nhi             = 1/timeStepHours;
q_in_mean       = 0.82;

% You may need to change this, according to your locale
startDateTimeStr = '02.09.2019 00:00:00';
startDateTime   = datetime(startDateTimeStr);
dateTimeVector  = startDateTime:hours(timeStepHours): ...
    (startDateTime+days(daysTotal)-hours(timeStepHours));

var1            = ones(hoursTotal*nhi, 3);
var2            = q_in_mean*ones(hoursTotal*nhi, 1);

tableFull       = table(dateTimeVector.', var1, var2);

While this works, I get tableFull.var2 in it's old shape, though I would like to have a (hoursTotal*nhi, 5) table, i.e., one separate table column for each array column. This would work if all elements were from the same data type:

tableFull       = array2table([dateTimeVector.', var1, var2])

And while this works, it does not seem very elegant:

tableFull       = horzcat(table(dateTimeVector.'), array2table(var1), table(var2));

Is there a better way to get a (hoursTotal*nhi, 5) table from those three variables with different data types?


Solution

  • Starting in R2018a, you can use splitvars to do this, i.e.

    >> splitvars(tableFull)
    ans =
      192×5 table
                Var1            var1_1    var1_2    var1_3    var2
        ____________________    ______    ______    ______    ____
        02-Sep-2019 00:00:00      1         1         1       0.82
        02-Sep-2019 00:15:00      1         1         1       0.82
    ...
    ...
    

    Another option for this particular case might be making a timetable like this

    >> array2timetable([var1, var2], 'RowTimes', dateTimeVector.')
    ans =
      192×4 timetable
                Time            Var1    Var2    Var3    Var4
        ____________________    ____    ____    ____    ____
        02-Sep-2019 00:00:00     1       1       1      0.82
        02-Sep-2019 00:15:00     1       1       1      0.82
    ...
    ...
    

    BTW, to parse the date strings independent of locale, you can use 'InputFormat' to write

    startDateTime = datetime(startDateTimeStr, 'InputFormat', 'dd.MM.yyyy HH:mm:ss');