计算由零分隔的比赛次数 [英] Count number of bouts separated by zeros
问题描述
我有一个这样的向量:
A = [1 2 1 1 1 4 5 0 0 1 2 0 2 3 2 2 2 0 0 0 0 33]
我想计算它包含多少组非零元素并保存它们.
I would like to count how many GROUPS of non zero elements it contains and save them.
所以我想隔离:
[1 2 1 1 1 4 5]
[1 2 1 1 1 4 5]
[1 2]
[2 3 2 2 2]
[2 3 2 2 2]
[33]
然后计算组数(它们应该是 4 个):)
and then count the groups (they should be 4) :)
你能帮我吗?
谢谢
推荐答案
使用 逻辑索引是:
count = sum(diff([A 0]==0)==1)
这假设 A
是您示例中的行向量.这适用于无零、全零、空向量和我尝试过的其他几个测试用例.
This assumes that A
is a row vector as in your example. This works with no zeros, all zeros, the empty vector, and several other test cases I tried.
要自己获取您的值组,您可以使用一个变体来my回答类似问题:
To obtain your groups of values themselves, you can use a variation to my answer to a similar question:
a0 = (A~=0);
d = diff(a0);
start = find([a0(1) d]==1) % Start index of each group
len = find([d -a0(end)]==-1)-start+1 % Length, number of indexes in each group
在您的情况下,将 len
替换为
In your case it might make sense to replace len
with
finish = find([d -a0(end)]==-1) % Last index of each group
start
、len
和finish
的length
应该与count
所以如果你需要分手,你可以使用它.然后,您可以使用 start
和 len
(或 finish
)将您的组存储在元胞数组或结构体或其他一些参差不齐的数组中.例如:
The length
of start
, len
, and finish
should be the same as the value of count
so you could just use this if you need to do the breaking up. You can then use start
and len
(or finish
) to store your groups in a cell array or struct or some other ragged array. For example:
count = length(start);
B = cell(count,1);
for i = 1:count
B{i} = A(start(i):finish(i));
end
这篇关于计算由零分隔的比赛次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!