Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

matlab - How to count number of 1 and 0 in the matrix?

I have an image of which I cut out only one column. After that I made it to be logical so there are be only 0 and 1 in this column.

Suppose my values in this column are

1111000110000000000000011111111

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

The result would be

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

I know only count for the entire column but I can't do it for each distinct block. Anyone please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let vec be a row vector (1-by-n) of 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, while data will tell you for each block if it is zero or one.

This question is closely related to run length coding.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...