I have large matrix and i want to find the number of consecutive zeros if there is more than 10 disply(hole) and give the index of the start and end of this vector of zeros,
4 views (last 30 days)
Show older comments
x=[1 0 1 4 8 4 3 5 9 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 0 0 0 0 2 4 4 4 4 0 0 0 0 0 0 0 0 0 3 5 6 3 0 0 0 0 4 4 4 0 0 0 0 5 4 1 0 0 0 0 0 4 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 ]
how can i find the start and end index of sequence of zeros if the length more than 10?
x=[1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 2 2 0 0 0 1 1 0 0 0 0 4 4 ];
c=0;k=0;z=0;
for i=1:length(x);
if x(i)==0;
c=c+1;
else
k=k+x(i);
if c>10;
disp(c);
disp('hole');
else
c=0;
end
end
end
Accepted Answer
Guillaume
on 23 Dec 2018
x=[1 0 1 4 8 4 3 5 9 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 0 0 0 0 2 4 4 4 4 0 0 0 0 0 0 0 0 0 3 5 6 3 0 0 0 0 4 4 4 0 0 0 0 5 4 1 0 0 0 0 0 4 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 ]
transitions = find(diff([1, x ~= 0, 1]));
runstarts = transitions(1:2:end);
runends = transitions(2:2:end) - 1;
runlengths = runends - runstarts + 1;
tokeep = runlengths >= 10;
runstarts = runstarts(tokeep)
runends = runends(tokeep)
More Answers (1)
Rik
on 23 Dec 2018
x=[1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 2 2 0 0 0 1 1 0 0 0 0 4 4];
%use this:
%[b,n]=RunLength(x);
%or this:
ii = [ find(x(1:end-1) ~= x(2:end)) length(x) ];
n = diff([ 0 ii ]);
b = x(ii);
clc
idx= b==0 & n>=10;
for k=find(idx)
start=1+sum(n(1:(k-1)));stop=start+n(k)-1;
fprintf('hole from %d to %d\n',start,stop)
end
3 Comments
Rik
on 24 Dec 2018
Sure, but you did not accept my answer, so I expect you aren't using my code anyway. But here is the edit:
x=[1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 2 2 0 0 0 1 1 0 0 0 0 4 4];
%use this:
%[b,n]=RunLength(x);
%or this:
ii = [ find(x(1:end-1) ~= x(2:end)) length(x) ];
n = diff([ 0 ii ]);
b = x(ii);
clc
idx= b==0 & n>=10;
if any(idx)
for k=find(idx)
start=1+sum(n(1:(k-1)));stop=start+n(k)-1;
fprintf('hole from %d to %d\n',start,stop)
end
else
disp('no holes')
end
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!