How can I match rows from two tables by timestamp and create a new table?
Show older comments
I am working with two sets of data that have timestamps that do not match up exactly, but I need to join the table rows by matching the timestamps that are approximately 30 minutes apart. Here is an example of the two different tables, and the end result that I am looking for:
T1 =
Obs Time Var1 Var2 Var3 Var(n)...
1 2/2/2017 11:00 1 2 3
2
3
4
...
T2=
Obs Time Var4
1 2/2/2017 10:40 1
2
I am hoping to have a matched table that will look like this:
T3 =
Obs Time (from T1) Time (from T2) Var1 Var2 Var3 Var4(from T2)
1
2
3
Answers (1)
Guillaume
on 2 Feb 2017
Assuming R2016b, convert your tables to Timetables and use withtol to match rows. This assumes that all rows of the first table will be match:
tt1 = table2timetable(t1);
tt2 = table2timetable(t2);
s = withtol(tt1.Time, minutes(30));
joinedtt = [tt1, tt2(s, 'Var4')]
5 Comments
William Pierce
on 2 Feb 2017
Walter Roberson
on 2 Feb 2017
Yes, withtol() can help with that. https://www.mathworks.com/help/matlab/matlab_prog/subscript-into-times-of-timetable.html
You would give the T2 timestamps as input to the withtol() and then use the output of the withtol() to index T1
As Walter says, if there can be non-matched rows in both tables:
tt1 = table2timetable(t1);
tt2 = table2timetable(t2);
S = withtol(tt1.Time, minutes(30));
tt2 = tt2(S, :);
S = withtol(tt2.Time, minutes(30));
joinedtt = [tt1(S, :), tt2(:, 'Var4')]
ought to work (as long as no two rows in one table match the same row in the other).
William Pierce
on 2 Feb 2017
Walter Roberson
on 3 Feb 2017
Sorry, timetables() are new in R2016b.
Categories
Find more on Common Operations 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!