在Matlab

时间:2015-12-09 00:28:42

标签: matlab vector counting

假设我在Matlab中有以下向量:

V = [0,1,0,0,0,1,...,1]。该向量仅包含01 s,条目总数为125。

我需要做两件事:

首先,我需要找到第一组具有八个元素的连续1,从最后一次观察开始。

例如:

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,...]

我有兴趣确定1上的第二个集合并检索集合中最后一个1的确切位置。

我的第二个问题与第一个问题有关。一旦我得到了集合中最后1的确切位置。我需要在连续八个条目中计算六个0

在上面给出的例子中:

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...]

我需要识别每个条目,直到我在一组八个中找到6个0

1 个答案:

答案 0 :(得分:2)

这很有趣。不确定这是最好的方法,我不做任何错误检查(如果没有8个1或6个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);