如何计算矩阵列中值的游程长度? [英] How to count length of runs of values in matrix columns?

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

问题描述

我有一个由列向量组成的矩阵,其值取0或1.我希望实现的是拥有某种形式的自动化过程,该过程可以创建一个简约的结构来显示结果.也就是说,该过程将为每个列变量创建与每个序列中连续1的数量相对应的结果向量v1,v2,v3,v4,v5.

I have a matrix made up of column vectors with values that either take on 0 or 1. What I wish to achieve is to have some form of automated process that creates a parsimonious structure to display the result. That is the process will create the result vectors v1,v2,v3,v4,v5 that correspond to the number of consecutive 1's in each sequence for each column variable.

例如d =

 0 1 1 1 1 
 1 1 0 0 0
 1 1 1 0 1
 0 0 0 0 0
 1 1 0 1 1

我们得到 v1 = [2,1] v2 = [3,1] v3 = [1,1] v4 = [1,1] v5 = [1,1,1]

And we get v1=[2,1] v2=[3,1] v3=[1,1] v4=[1,1] v5=[1,1,1]

推荐答案

该方法无循环.

代码应该是不言自明的,否则请问我.结果变量是一个单元格数组,因为对于d的每一列,结果的大小都不同.

The code should be self-explanatory, otherwise ask me. The result variable is a cell array, because the result has a different size for each column of d.

nrows = size(d,1);
d_neg_cell = num2cell(~d,[nrows 1]);
zeros_d = cellfun(@find, d_neg_cell, 'UniformOutput', 0);
find_runs = @(v) nonzeros( diff([0; v; nrows+1])-1 ).';
sol = cellfun(find_runs, zeros_d, 'UniformOutput', 0);

对于您的d矩阵,得出:

>> sol{:}
ans =
     2     1
ans =
     3     1
ans =
     1     1
ans =
     1     1
ans =
     1     1     1

这篇关于如何计算矩阵列中值的游程长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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