Detecting length and number of occurrences in a logical array
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jason MacNaughton
le 25 Nov 2019
Commenté : Image Analyst
le 8 Juin 2022
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 commentaires
Réponse acceptée
the cyclist
le 25 Nov 2019
Modifié(e) : the cyclist
le 25 Nov 2019
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
Plus de réponses (2)
Image Analyst
le 25 Nov 2019
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
le 25 Nov 2019
Modifié(e) : Andrei Bobrov
le 26 Nov 2019
Without Toolboxes and Fileexchanges
a = accumarray(cumsum([0;diff(array1(:))] == 1).*array1(:)+1,1);
out = a(2:end);
4 commentaires
Amanda Beatty
le 8 Juin 2022
@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 :)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!