2011-01-27 59 views
2

我目前有两个时间轴(timeline1和timeline2),以及匹配的数据(data1和data2)。时间表几乎相同,但不完全相同(约为常见值的90%)。如何在Matlab中优化这个时间轴匹配代码?

我试图找到数据1和数据2对应于相同的时间戳值(忽略所有其他值)

我的第一个简单的实现如下(和显然是非常缓慢的,因为我的时间表包含数千的值)。任何想法如何改善?我敢肯定有这样做,同时避免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)) = []; 

回答

2

不能你刚才叫INTERSECT

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

可以用Matlab的intersect功能:

c = intersect(A, B) 
+0

啊哈!我知道必须有东西(我只是不知道相交)谢谢! – Kena 2011-01-27 16:39:53

1

您需要使用索引从intersect返回。

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