我目前有两个时间轴(timeline1和timeline2),带有匹配的数据(data1和data2)。时间表差不多,但不太匹配(大约90%的常见值)。
我正在尝试从data1和data2中找到对应于相同时间戳的值(忽略所有其他值)
我的第一个简单实现如下(鉴于我的时间轴包含数千个值,显然非常慢)。关于如何改进这个的任何想法?我确信有一种聪明的方法可以避免for循环或查找操作......
% We expect the common timeline to contain
% 0 1 4 5 9
timeline1 = [0 1 4 5 7 8 9 10];
timeline2 = [0 1 2 4 5 6 9];
% Some bogus data
data1 = timeline1*10;
data2 = timeline2*20;
reconstructedData1 = data1;
reconstructedData2 = zeros(size(data1));
currentSearchPosition = 1;
for t = 1:length(timeline1)
% We only look beyond the previous matching location, to speed up find
matchingIndex = find(timeline2(currentSearchPosition:end) == timeline1(t), 1);
if isempty(matchingIndex)
reconstructedData1(t) = nan;
reconstructedData2(t) = nan;
else
reconstructedData2(t) = data2(matchingIndex+currentSearchPosition-1);
currentSearchPosition = currentSearchPosition+matchingIndex;
end
end
% Remove values from data1 for which no match was found in data2
reconstructedData1(isnan(reconstructedData1)) = [];
reconstructedData2(isnan(reconstructedData2)) = [];
答案 0 :(得分:3)
您可以使用Matlab的intersect
函数:
c = intersect(A, B)
答案 1 :(得分:2)
你不能打电话给INTERSECT吗?
commonTimeline = intersect(timeline1,timeline2);
commonTimeline =
0 1 4 5 9
答案 2 :(得分:1)
您需要使用从intersect
返回的索引。
[~ ia ib] = intersect(timeline1, timeline2);
recondata1 = data1(ia);
recondata2 = data2(ib);