how to count the number of zeros between 2 one's

4 ビュー (過去 30 日間)
Monika  Kok
Monika Kok 2016 年 4 月 24 日
編集済み: per isakson 2017 年 5 月 5 日
i am using the code
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0];
num = num(find(num==1, 1, 'first'):find(num==1, 1, 'last'));
% Measure the lengths of the stretches/runs of zeros.
measurements = regionprops(logical(~num), 'Area');
zerospan = [measurements.Area]
a = max(zerospan)
this is giving me answer as 9 which is correct for middle part. but i would also count the end around number of zeros. that is zeros starting from second last position and ending at fourth position. which should give me answer as 6.
thanks monica

採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 4 月 24 日
編集済み: Andrei Bobrov 2016 年 4 月 24 日
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0]
measurements = regionprops(logical(~num), 'Area')
m = [measurements.Area];
out = [sum(m([1,end])), max(m(2:end-1))]
  1 件のコメント
Image Analyst
Image Analyst 2016 年 4 月 24 日
"which should give me answer as 6." Just be aware that this answer gives [6,9].

サインインしてコメントする。

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 4 月 24 日
編集済み: Azzi Abdelmalek 2016 年 4 月 24 日
nu=~num;
s=cumsum(num)+~num(1);
ii=strfind(num,[1 0]);
jj=zeros(size(num));
jj(ii)=1;
s=s+cumsum(jj)
f=accumarray(s',(1:numel(s))',[],@(x) sum(nu(x)));
out=[ nonzeros(f(2:end-1))' sum([f(1) f(end)])]
  2 件のコメント
Monika  Kok
Monika Kok 2016 年 4 月 24 日
thnq so much i was exactly looking for this only.
can you show me an approach by which i can get the starting location of maximum zero span for example: [1 0 0 0 1 0 0 0 0 0 0 0 1 1 1 1 1 0 1 ] in this case maximum zero span is starting from location 5.
thnx monica
Image Analyst
Image Analyst 2016 年 4 月 24 日
You almost had it. You just needed to ask for the 'PixelIdxList' when you called regionprops. This gives you the index of every element in each grouping of 0's.
num = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0];
% Measure the lengths of the stretches/runs of zeros.
measurements = regionprops(logical(~num), 'Area', 'PixelIdxList');
zerospan = [measurements.Area]
% Get index of the largest run in the lengths array:
[longestRun, indexOfLongestRun] = max(zerospan)
% Get the index in the original num array:
indexOfStartOfLongestRun = measurements(indexOfLongestRun).PixelIdxList(1)
You will see that indexOfLongestRun = 9, which is where that run starts at.

サインインしてコメントする。


Image Analyst
Image Analyst 2016 年 4 月 24 日
Just add the first and last area:
result = zerospan(1) + zerospan(end);

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by