How to group logical numbers in a vector?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Khaldon Qaid
el 12 de Jun. de 2022
Comentada: Khaldon Qaid
el 13 de Jun. de 2022
I am trying to count how many groups of ones in a vector. Number 1 repeated three times in three positions in this vector.
Vector = [1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1];
The expected answer is
Num_gr_1 = 3
Could you help please?
2 comentarios
Respuesta aceptada
Más respuestas (2)
dpb
el 12 de Jun. de 2022
>> num_gr_1=sum(diff(Vector)==1)+(Vector(1)==1)
num_gr_1 =
3
>>
There are FEX submissions for runlength encoding that will give you all the details besides just the number of groups asked for here...if you want/need the locations of the groups,
>> gr_1=find([0 diff(Vector)]==1)
gr_1 =
1 8 18
>>
Above is specific for [0, 1]; the FEX submissions will find any/all runs. The above logic will deal with any specific values by converting the input vector to logical based on the looked-for value, but that's the limit to its flexibility.
But, it's quick/simple for the specific task.
Image Analyst
el 12 de Jun. de 2022
If you have the Image Processing Toolbox you can label each group and count them in a single line of code with bwlabel :
Vector = [1 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1]; % Sample data
[L, Num_gr_1] = bwlabel(Vector) % Label groups and count groups.
Ver también
Categorías
Más información sobre Data Type Conversion 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!