如何计算矩阵中的1和0的数量? [英] How to count number of 1 and 0 in the matrix?

查看:456
本文介绍了如何计算矩阵中的1和0的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片,我只剪了一列。之后我把它变成了逻辑,所以这一栏中只有0和1。

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.

结果将是

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.

推荐答案

vec 成为向量(1-by - n )的零和1,然后您可以使用以下代码

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 会给你连续的数字零和一,而数据将告诉您每个块是否为零或一个。

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.

此问题与运行长度密切相关编码

演示:

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

这篇关于如何计算矩阵中的1和0的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆