我有两个单元格数组tb_ref
和tb_test
,内容如下:
tb_ref = {'2009-04-13 10:50:00.000' 6.0708560 339.81910; ...
'2009-04-13 11:00:00.000' 6.1039610 333.53540; ...
'2009-04-13 11:10:00.000' 5.2654460 217.59230; ...
'2009-04-13 12:00:00.000' 6.4318040 362.63540; ...
'2009-04-13 12:10:00.000' 7.1082010 565.98960; ...
'2009-04-13 12:20:00.000' 6.2918340 440.54640; ...
'2009-04-13 12:50:00.000' 8.0200310 757.24960};
tb_test = {'13-Apr-2009 10:50:00' 3.1; ...
'13-Apr-2009 11:00:00' 33; ...
'13-Apr-2009 11:10:00' 21; ...
'13-Apr-2009 11:20:00' 160; ...
'13-Apr-2009 11:30:00' 143; ...
'13-Apr-2009 11:40:00' 74; ...
'13-Apr-2009 11:50:00' 39; ...
'13-Apr-2009 12:00:00' 36; ...
'13-Apr-2009 12:10:00' 56; ...
'13-Apr-2009 12:20:00' 44; ...
'13-Apr-2009 12:30:00' 20; ...
'13-Apr-2009 12:40:00' 34; ...
'13-Apr-2009 12:50:00' 75};
我想从两个数组中选择时间戳匹配的数据,并将其存储在新的单元格数组中。例如,2009-04-13 10:50:00.000
匹配两个数组,因此新数组必须具有以下值:
'2009-04-13 10:50:00.000' 6.0708560 339.81910 3.1
等等。我怎么能这样做?
答案 0 :(得分:2)
为确保日期格式符合各组,最好使用datestr
首先格式化两个中的日期:
tb_ref(:, 1) = cellstr(datestr(tb_ref(:, 1), 'yyyy-mm-dd HH:MM:SS.FFF'));
tb_test(:, 1) = cellstr(datestr(tb_test(:, 1), 'yyyy-mm-dd HH:MM:SS.FFF'));
现在,假设每个时间戳只能在每个集合中出现一次,您可以使用intersect
找到常用条目并将它们组合成一个新的单元格数组:
[dates, indexRef, indexTest] = intersect(tb_ref(:, 1), tb_test(:, 1));
tb_new = [dates tb_ref(indexRef, 2:3) tb_test(indexTest, 2)];
以上是您应该为上述示例获得的结果:
tb_new =
7×4 cell array
'2009-04-13 10:50:00.000' [6.0709] [339.8191] [3.1000]
'2009-04-13 11:00:00.000' [6.1040] [333.5354] [ 33]
'2009-04-13 11:10:00.000' [5.2654] [217.5923] [ 21]
'2009-04-13 12:00:00.000' [6.4318] [362.6354] [ 36]
'2009-04-13 12:10:00.000' [7.1082] [565.9896] [ 56]
'2009-04-13 12:20:00.000' [6.2918] [440.5464] [ 44]
'2009-04-13 12:50:00.000' [8.0200] [757.2496] [ 75]