How to count the number 1 and 0 in a matrix?

I have an image from which I cut only one column. After that, I made it logical, so there should only be 0 and 1 in this column.

Assume my values ​​in this column

1111000110000000000000011111111 

I want to count the length of each block of them or each block of zeros.

Result will be

 1 - 4 (first 1) 0 - 3 (first 0) 1 - 2 and so on... 

I know only the number for the entire column, but I can not do this for each individual block. Someone please help me.

+3
source share
1 answer

Let vec be row (1-by- n ) zeros and ones, then you can use the following code

 rl = ( find( vec ~= [vec(2:end), vec(end)+1] ) ); data = vec( rl ); rl(2:end) = rl(2:end) - rl(1:end-1); 

rl will give you the number of consecutive zeros and ones, and data will tell you about each block if it is zero or one.

This issue is closely related to the path length .

Demo:

 vec = [1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1]; rl = ( find( vec ~= [vec(2:end), vec(end)+1] ) ); data = vec( rl ), rl(2:end) = rl(2:end) - rl(1:end-1), data = 1 0 1 0 1 rl = 4 3 2 14 8 
+6
source

Source: https://habr.com/ru/post/1484196/


All Articles