[英]Counting sets and vector positions in Matlab
Suppose I have the following vector in Matlab: 假设我在Matlab中有以下向量:
V = [0,1,0,0,0,1,...,1]
. V = [0,1,0,0,0,1,...,1]
The vector only contains 0
and 1
s and the total number of entries is 125. 该向量仅包含
0
和1
s,条目总数为125。
I need to do two things: 我需要做两件事:
First, I need to find the first set of consecutive 1
s with exactly eight elements, starting with the last observation. 首先,我需要找到第一组连续的
1
s,它们具有恰好八个元素,从最后一次观察开始。
For example in: 例如:
V = [0,1,...,1,1,1,1,1,1,1,1,0,1,0,...,1,1,1,1,1,1,1,1,...,0,0,1,0,1,0,0,1,0,1,...]
I would be interested in identifying the second set on 1
s and retrieving the exact position of the last 1
in the set. 我将有兴趣确定在第二组
1
秒和检索的最后的精确位置1
中的集。
My second problem is related to the first one. 我的第二个问题与第一个有关。 Once I have the exact position of the last
1
in the set. 一旦我有了集合中最后
1
的确切位置。 I need to count six 0
s on eight consecutive entries. 我需要在八个连续的条目上计数六个
0
。
In the example given above: 在上面的示例中:
V = [0,1,...,1,1,1,1,1,1,1,1,0,1,0,...,1,1,1,1,1,1,1,1,...,0,0,1,0,1,0,0,1,0,1...]
I would need identify each entry until I found 6 0
s in a set of eight. 我需要确定每个条目,直到在八个集合中找到6
0
s为止。
This is fun. 这好有趣。 Not sure this is the best approach, and I don't do any error checking (in case there are no sequences of eight 1s or six 0s):
不确定这是最好的方法,并且我不执行任何错误检查(如果没有八个1或六个0的序列):
%// Testing with this vector
v = [0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0];
n_v = numel(v);
%// The trick is to construct a vector summing eight consecutive entries
v_s = arrayfun(@(ii) sum(v((0:7) + ii)), 1:(n_v - 7));
%// when we find entries equal to 8, we have found eight consecutive 1s
v_8 = find(v_s == 8);
%// Likewise, entries equal to 2 correspond to six zeros (in any order)
v_6_0 = find(v_s == 2);
%// We then find sequence of eight 1s followed by six 0s
v_8_with_6_0 = v_8(arrayfun(@(ii) any(ii<v_6_0), v_8));
%// ... and pick the last one
v_8_with_6_0 = v_8_with_6_0(end);
%// then we get the start of that sequence of 0s
v_6_0_pos = v_6_0(find(v_8_with_6_0 < v_6_0, 1));
%// Print result (add 7 to find last of 8)
fprintf('Last sequence of eight 1s with a following sequence containing six 0s ends at %i, and the sequence of 0s starts at %i.\n', v_8_with_6_0 + 7, v_6_0_pos);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.