[英]How can I optimize this timeline-matching code in Matlab?
我目前有兩個時間軸(時間軸1和時間軸2),並具有匹配的數據(數據1和數據2)。 時間軸幾乎匹配,但不完全匹配(約占普通值的90%)。
我正在嘗試從data1和data2中找到與相同時間戳相對應的值(忽略所有其他值)
我的第一個瑣碎的實現如下(鑒於我的時間軸包含數千個值,顯然很慢)。 關於如何改善這一點的任何想法? 我敢肯定有一種聰明的方法可以做到這一點,同時避免了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)
你不可以打INTERSECT嗎?
commonTimeline = intersect(timeline1,timeline2);
commonTimeline =
0 1 4 5 9
您需要使用從intersect
返回的索引。
[~ ia ib] = intersect(timeline1, timeline2);
recondata1 = data1(ia);
recondata2 = data2(ib);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.