Detecting length and number of occurrences in a logical array
23 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
the cyclist
2019-11-25
编辑:the cyclist
2019-11-25
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
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
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
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!