Detecting length and number of occurrences in a logical array
23 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jason MacNaughton
el 25 de Nov. de 2019
Comentada: Image Analyst
el 8 de Jun. de 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 comentarios
Respuesta aceptada
the cyclist
el 25 de Nov. de 2019
Editada: the cyclist
el 25 de Nov. de 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
Más respuestas (2)
Image Analyst
el 25 de Nov. de 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
el 25 de Nov. de 2019
Editada: Andrei Bobrov
el 26 de Nov. de 2019
Without Toolboxes and Fileexchanges
a = accumarray(cumsum([0;diff(array1(:))] == 1).*array1(:)+1,1);
out = a(2:end);
4 comentarios
Amanda Beatty
el 8 de Jun. de 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 :)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!