Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...