2011-03-22 35 views
0

我有2個矩陣與SAME ID。我需要從mat1中提取這些行的ID,其日期在mat2中日期的±5天內。對於mat2也是相同的操作。請看這裏的數據:UNIQCols = [1 2] ; dateCol = [3] ; valueCol = [4] ; dayRange = +- 15days會員檢查和日期範圍檢查在Matlab

 % UniqCol Date Value 
mat1 = [2001 2 733427 1001 ; 
     2001 2 733793 2002 ; 
     2001 2 734582 2003 ; 
     3001 1 734220 30 ; 
     3001 1 734588 20 ;]; 
mat2 = [2001 2 733790 7777 ; 
     2001 2 734221 2222 ; 
     3001 1 734220 10 ; 
     3001 1 734588 40 ;] ; 

ans1 = [2001 2 733793 2002 ; 3001 1 734220 30 ; 3001 1 734588 20 ] ; 
ans2 = [2001 2 733790 7777 ; 3001 1 734220 10 ; 3001 1 734588 40 ] ; 

這需要是一個向量化的操作!這些ID按照日期的升序排列。日期在Q或年度基礎上分開。所以範圍將永遠是< <(date2-date1)請幫助和謝謝!

+0

你是否僅限於matlab來完成此任務? Matlab是用於矩陣處理的;這與正好處於矩陣形式的日期一起工作。您可能會更好地服務於其他腳本語言。 – eykanal 2011-03-22 16:45:15

+0

因此,您需要將'mat1'中的每一行與'mat2'中的每一行進行比較,以查看它們是否在±5天之內? – eykanal 2011-03-22 16:49:02

+0

對不起,最後一個請求...請問您可以編輯問題,將標籤分配給四列?我不確定是什麼。 – eykanal 2011-03-22 17:12:36

回答

0

這是一個基於我在評論中提到的similar question的功能。記住你的矩陣必須按日期排序。

function match_for_xn = match_by_distance(xn, xm, maxdist) 
%#Generates index for elements in vector xn that close to any of elements in 
%#vector xm at least by distance maxdist 

match_for_xn = false(length(xn), 1); 
last_M = 1; 
for N = 1:length(xn) 
    %# search through M until we find a match. 
    for M = last_M:length(xm) 
    dist_to_curr = xm(M) - xn(N); 
    if abs(dist_to_curr) < maxdist 
     match_for_xn(N) = 1; 
     last_M = M; 
     break 
    elseif dist_to_curr > 0 
     last_M = M; 
     break 
    else 
     continue 
    end 

    end %# M 
end %# N 

而且測試腳本:

mat1 = sortrows([ 
     2001 2 733427 1001 ; 
     2001 2 733793 2002 ; 
     2001 2 734582 2003 ; 
     3001 1 734220 30 ; 
     3001 1 734588 20 ; 
     ],3); 
mat2 = sortrows([ 
     2001 2 733790 7777 ; 
     2001 2 734221 2222 ; 
     3001 1 734220 10 ; 
     3001 1 734588 40 ; 
     ],3); 

mat1_index = match_by_distance(mat1(:,3),mat2(:,3),5); 
ans1 = mat1(mat1_index,:); 
mat2_index = match_by_distance(mat2(:,3),mat1(:,3),5); 
ans2 = mat2(mat2_index,:); 

我還沒有嘗試過你的問題的任何解決方案矢量。如果您對該解決方案進行了任何嘗試,並檢查時序和內存消耗(包括排序步驟)。

+0

嗨唷..感謝您的回覆。此代碼確實符合範圍內的日期,但這些日期需要在ID的子組內進行檢查(列1和列2)。簡而言之,假設您從mat1中獲取AAPL的行,並在mat2中搜索AAPL的行中的日期。行數可以不同。你可以請建議使用準確的做法嗎? – Maddy 2011-03-29 21:00:47