2014-05-21 57 views
2

這是我試圖找到大於或等於5的連續零的代碼。在Matlab中查找五個或更多個連續的零的運行

a=[0,0,0,0,0,0,0,0,9,8,5,6,0,0,0,0,0,0,3,4,6,8,0,0,9,8,4,0,0,7,8,9,5,0,0,0,0,0,8,9,0,5,8,7,0,0,0,0,0]; 

[x,y]=size(a); 

for i=0:y 
i+1; 
k=1; 
l=0; 
n=i; 
count=0; 

while (a==0) 
count+1; 
break; 
n+1; 
end 
if(count>=5) 
v([]); 
for l=k:l<n 
v(m)=l+1; 
m+1; 
end  
end  
count=1; 
i=n; 
end  
for i = o : i<m 
i+1; 

fprintf('index of continous zero more than 5 or equal=%d',v(i)); 

end 

回答

6

如果你想找到的n或多個零運行的起點指數:

v = find(conv(double(a==0),ones(1,n),'valid')==n); %// find n zeros 
v = v([true diff(v)>n]); %// remove similar indices, indicating n+1, n+2... zeros 

在你的榜樣,這給

v = 
    1 13 34 45 
+0

那麼優雅,耶! –

+0

如果我們想要找到中間零索引而不是開始零索引,那麼該怎麼辦,即v = 4 16等 –

+1

@FarazAhmad使用'v +(n + 1)/ 2'? –

1

一個班輪strfind辦法找到起始指數爲5連續的零 -

out = strfind(['0' num2str(a==0,'%1d')],'011111') 

輸出 -

out = 

    1 13 34 45 

上面的代碼可以推廣這樣的 -

n = 5 %// number of consecutive matches 
match = 0 %// match to be used 
out = strfind(['0' num2str(a==match,'%1d')],['0' repmat('1',1,n)]) %// starting indices of n consecutive matches 

如果你想找到所有在n連勝被發現的指數,你可以添加此代碼 -

outb = strfind([num2str(a==match,'%1d'),'0'],[repmat('1',1,n) '0'])+n-1 
allind = find(any(bsxfun(@ge,1:numel(a),out') & bsxfun(@le,1:numel(a),outb'))) 
+0

不錯! @Divakar –

+0

謝謝塞爾吉奧! :) – Divakar

+0

這裏有兩件非常優雅的事情。 1)你把「哨兵0」放在字符串的前面,這樣你就可以找到一個運行的開始;和2)使用'a == 0'將數字轉換爲一個布爾數組(因此很容易將其轉換爲任何其他條件)。但是你有一個輸入錯誤 - 在第二個例子中,'num2str(a == 0'應該是'num2str(a == match')。 – Floris

0

如果您想查找一般情況下的了「矢量V n或多個值x的運行」,你可以做到以下幾點:

% your particular case: 
n = 5; 
x = 0; 
V = [0,0,0,0,0,0,0,0,9,8,5,6,0,0,0,0, ... 
    0,0,3,4,6,8,0,0,9,8,4,0,0,7,8,9, ... 
    5,0,0,0,0,0,8,9,0,5,8,7,0,0,0,0,0]; 


b = (V == x); % create boolean array: ones and zeros 
d = diff([0 b 0]); % turn the start and end of a run into +1 and -1 
startRun = find(d==1); 
endRun = find(d==-1); 
runlength = endRun - startRun; 
answer = find(runlength > n); 
runs = runlength(answer); 
disp([answer(:) runs(:)]); 

這將顯示運行開始,其長度,所有實驗>值X的N個。