Detecting length and number of occurrences in a logical array

조회 수: 23 (최근 30일)
Jason MacNaughton
Jason MacNaughton 2019년 11월 25일
댓글: Image Analyst 2022년 6월 8일
EX:
array1 = [0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 1]
I want to extract the number of times of consecutive 1's in a separate array eg: array2 = [4 2 6 1], where the length of array 2 is equal to the amount of groups of consecutive 1s and the values is the length of the chain of 1s. I also want to ensure that at 1's at the beginning and end of the arrays are captured.

채택된 답변

the cyclist
the cyclist 2019년 11월 25일
편집: the cyclist 2019년 11월 25일
Download Jan's RunLength utility from the File Exchange. It will do exactly what you want.
array1 = [0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 1];
[b n] = RunLength(array1);
array2 = n(b==1)
array2 =
4 2 6 1

추가 답변 (2개)

Image Analyst
Image Analyst 2019년 11월 25일
Jason, if you want a simple way to do it using built-in Mathworks functions and without using some third party File Exchange submission, and if you have the Image Processing Toolbox, you can simply use regionprops(). Here's an example:
array1 = [0 0 0 0 0 1 1 1 1 0 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 1]
props = regionprops(logical(array1), 'Area')
allLengths = [props.Area]
regionprops() labels each contiguous run of 1's and then measures each run and puts the results into a structure array.
props =
4×1 struct array with fields:
Area
Using the bracket trick in the third line concatenates all Area fields from the structure into one single vector.
allLengths =
4 2 6 1

Andrei Bobrov
Andrei Bobrov 2019년 11월 25일
편집: Andrei Bobrov 2019년 11월 26일
Without Toolboxes and Fileexchanges
a = accumarray(cumsum([0;diff(array1(:))] == 1).*array1(:)+1,1);
out = a(2:end);
  댓글 수: 4
Amanda Beatty
Amanda Beatty 2022년 6월 8일
@Image Analyst I don't have the image processing toolbox so I couldn't use regionprops. My array was array1 = [1 1 1 1 0].
%original
a = accumarray(cumsum([0;diff(array1(:))] == 1).*array1(:)+1,1);
out = a(2:end)
out =
1×0 empty double row vector
%my edit
a = accumarray(cumsum(diff([0;array1(:)]) == 1).*array1(:)+1,1);
out = a(2:end)
out =
4
I don't know, maybe I just had a typo or something that haven't noticed yet, but in the end it did the job, so that's what matters :)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by