简体   繁体   中英

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

I currently have two timelines (timeline1 and timeline2), with matching data (data1 and data2). Timelines almost, but not quite match (about 90% of common values).

I'm trying to find values from data1 and data2 that correspond to identical timestamps (ignoring all other values)

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...

% 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 ?

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

You need to use the indexes returned from intersect .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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