Detecting length and number of occurrences in a logical array

21 ビュー (過去 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 :)
Image Analyst
Image Analyst 2022 年 6 月 8 日
Maybe try findgroups

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by