在Matlab中查找五个或更多连续零的运行

时间:2014-05-21 11:36:07

标签: arrays matlab

这是我试图找到连续零的代码,大约为5或更多。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')))

答案 2 :(得分:0)

如果您想在向量V&#34;中找到&#34;运行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(:)]);

这将显示所有运行的运行开始及其长度&gt; n值x。