2

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?

winkmal
  • 622
  • 1
  • 6
  • 16
  • Does this sort you out? `tableFull = table( dateTimeVector.', var1(:,1), var1(:,2), var1(:,3), var2 )`? It's hard (for me) to understand how generic your solution needs to be based on this example. – Wolfie Sep 02 '19 at 12:58

1 Answers1

3

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');
Edric
  • 23,676
  • 2
  • 38
  • 40
  • Thanks for pointing me towards `timetable`, very useful! The only thing I don't really get: `timetable` was introduced in R2016b, while `writetimetable` was introduced in R2019a. Since I am currently on R2018a, I need to convert the timetable back to a regular table, via `timetable2table`, so I can use the `writetable` function. A bit clumsy, but I can live with that. – winkmal Sep 04 '19 at 08:52