Count size of groups of 1's

5 visualizaciones (últimos 30 días)
David AR
David AR el 3 de Mayo de 2019
Respondida: Pablo Rozier-Delgado el 13 de Jul. de 2023
Hi all, this is my first question on the forum.
I have a vector called gpos that have 1's where I have a NaN value (gpos = isnan(data);)
For example
gpos = [1 1 1 0 0 1 1 0 1 1]'
I'd like to count the size of groups of 1's, like my expected result. How do I accomplish that? Thanks in advance.
result = [3 2 2]' % ignoring data that is zero

Respuesta aceptada

Erivelton Gualter
Erivelton Gualter el 3 de Mayo de 2019
Here is a way you can perform this:
gpos = [1 1 1 0 0 1 1 0 1 1]';
[I, ~] = find(gpos == 1);
k = 0;
result = [];
for i=2:length(I)
if (I(i)-I(i-1)) ~= 1
result = [result; k+1];
k = 0;
else
k = k + 1;
end
end
result = [result; k+1];
disp(result);
But definetly, you might write something simpler .
  1 comentario
Matt J
Matt J el 29 de Mzo. de 2021
David AR's comment moved here:
Thank you. The code works flawlessly. Best regards.

Iniciar sesión para comentar.

Más respuestas (1)

Pablo Rozier-Delgado
Pablo Rozier-Delgado el 13 de Jul. de 2023
Another way, without for loop:
gpos = [1 1 1 0 0 1 1 0 1 1]'; % Detected NaNs
indGroups = bwlabel(gpos) + 1; % Label groups of ones and make it positive integers
result = accumarray(indGroups,gpos); % sum of each groups
result(result == 0) = [] % delete the 0 group
result = 3×1
3 2 2

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by