MATLAB Answers

Combine timetables vertically different variables

32 views (last 30 days)
I have two timetables tt1 and tt2 each with different dates and I want to concatenate them vertically using tt12 = [tt1; tt2];
However, the issue is that tt1 and tt2 do not have all columns (variables) in common. I would need the variables that are present in both timetables to be combined (concatenated) vertically as usual, but also append any new variables to the final tt12, where missing dates in those new variables would be just NaN.
I cannot use synchronize as that creates tt12 with double number of variables (it does not merge the same variables into one column).
The new timetable tt12 would then have more columns (the unique union of all variables present in tt1 and tt2). The only thing I could think of is to manually prepare (expand) the timetables tt1 & tt2 so that they have the same variables (using ismember function on variable names, perhaps), before using the tt12 = [tt1; tt2];
Is there any easier function that would achieve this?

Accepted Answer

Duncan Po
Duncan Po on 11 Feb 2020
You can use outerjoin with MergeKeys option set to true. You need to specify your common variable names (in addition to 'Time') as the keys. See this example:
>> t1 = timetable(hours(1:5)', (1:5)', (6:10)', 'VariableNames', {'foo', 'bar'});
>> t2 = timetable(hours(6:10)', (1:5)', (6:10)', 'VariableNames', {'foo2', 'bar'});
>> t12 = outerjoin(t1, t2, 'Keys', [{'Time'}, intersect(t1.Properties.VariableNames, t2.Properties.VariableNames)], 'MergeKeys', true)
t12 =
10×3 timetable
Time foo bar foo2
_____ ___ ___ ____
1 hr 1 6 NaN
2 hr 2 7 NaN
3 hr 3 8 NaN
4 hr 4 9 NaN
5 hr 5 10 NaN
6 hr NaN 6 1
7 hr NaN 7 2
8 hr NaN 8 3
9 hr NaN 9 4
10 hr NaN 10 5
  1 Comment
Martin Kabelka
Martin Kabelka on 11 Feb 2020
Thank you Duncan, this is exactly what I was looking for!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!