简体   繁体   English

如何在Matlab中优化此时间轴匹配代码?

[英]How can I optimize this timeline-matching code in Matlab?

I currently have two timelines (timeline1 and timeline2), with matching data (data1 and data2). 我目前有两个时间轴(时间轴1和时间轴2),并具有匹配的数据(数据1和数据2)。 Timelines almost, but not quite match (about 90% of common values). 时间轴几乎匹配,但不完全匹配(约占普通值的90%)。

I'm trying to find values from data1 and data2 that correspond to identical timestamps (ignoring all other values) 我正在尝试从data1和data2中找到与相同时间戳相对应的值(忽略所有其他值)

My first trivial implementation is as follows (and is obviously terribly slow, given that my timelines contain thousands of values). 我的第一个琐碎的实现如下(鉴于我的时间轴包含数千个值,显然很慢)。 Any ideas on how to improve this? 关于如何改善这一点的任何想法? I'm sure there is a smart way of doing this while avoiding the for loop, or the find operation... 我敢肯定有一种聪明的方法可以做到这一点,同时避免了for循环或find操作。

% 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)) = [];

您可以使用Matlab的intersect函数:

c = intersect(A, B)

Couldn't you just call INTERSECT ? 你不可以打INTERSECT吗?

commonTimeline = intersect(timeline1,timeline2);
commonTimeline =
     0     1     4     5     9

You need to use the indexes returned from intersect . 您需要使用从intersect返回的索引。

[~ ia ib] = intersect(timeline1, timeline2);
recondata1 = data1(ia);
recondata2 = data2(ib);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM