2016-12-28 40 views
0

我有一個單元是這樣的:在matlab中查找單元格內模式的出現次數?

x = {'3D' 
    'B4' 
    'EF' 
    'D8' 
    'E7' 
    '6C' 
    '33' 
    '37'} 

我們假設細胞是1000x1。我想找到這個單元格內pattern = [30;30;64;63]的出現次數,但是按照顯示的順序。換句話說,首先檢查x{1,1},x{2,1},x{3,1},x{4,1} 然後檢查x{2,1},x{3,1},x{4,1},x{5,1}並且像這樣直到單元格的末尾並返回它的出現次數。

這是我的代碼,但它沒有奏效!

while (size (pattern)< size(x)) 
    count = 0; 
    for i=1:size(x)-length(pattern)+1 
     if size(abs(x(i:i+size(pattern)-1)-x))==0 
      count = count+1; 
     end 
    end 
end 
+0

你的單元格'x'看起來像十六進制值,對不對?如果這個單元格是一個十進制數的數組,它將更容易識別一個模式。 – obchardon

+0

是的,但我需要找到這種模式之間的十六進制值 – lighting

回答

0

你的示例代碼有幾個問題 - 最重要的是我不相信你在做任何比較操作,這將是必要的,以確定內的模式的出現搜索數據(x)。此外,x模式之間存在可變類型不匹配 - 一個是字符串的單元陣列,另一個是十進制數組。要解決這個問題

一種方式是重組X模式爲字符串,然後用strfind找到模式的出現。只有在任何一個變量中沒有丟失數據的情況下,該方法纔會起作用。

x = {'3D';'B4';'EF';'D8';'E7';'6C';'33';'37';'xE';'FD';'8y'}; 
pattern = {'EF','D8'}; 

collated_x=[x{:}]; 
collated_pattern = [pattern{:}]; 
found_locations = strfind(collated_x, collated_pattern); 

% Remove 'offset' matches that start at even locations 
found_locations = found_locations(mod(found_locations,2)==1); 

count = length(found_locations) 
+0

所以,如果我想找到一個模式與4字符串我應該寫像found_locations = found_locations(mod(found_locations,4)== 1);? – lighting

+0

是的,這就對了。你可以用下面的形式重寫我的代碼,使它更加靈活:'found_locations = found_locations(mod(found_locations,length(pattern))== 1);' – 4Oh4

0

使用字符串查找功能。 這是快速和簡單的解決方案:

clear 
str_pattern=['B4','EF']; %same as str_pattern=['B4EF']; 
x = {'3D' 
    'B4' 
    'EF' 
    'D8' 
    'EB' 
    '4E' 
    'F3' 
    'B4' 
    'EF' 
    '37'} ; 
str_x=horzcat(x{:}); 
inds0=strfind(str_x,str_pattern); %including in-middle 
inds1=inds0(bitand(inds0,1)==1); %exclude all in-middle results 

disp(str_x); 
disp(str_pattern); 
disp(inds0); 
disp(inds1); 
+0

謝謝!它的工作 – lighting

相關問題