Reputation: 182
Suppose I have the following vector in Matlab:
V = [0,1,0,0,0,1,...,1]
. The vector only contains 0
and 1
s and the total number of entries is 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.
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.
My second problem is related to the first one. Once I have the exact position of the last 1
in the set. I need to count six 0
s on eight consecutive entries.
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.
Upvotes: 1
Views: 61
Reputation: 5157
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):
%// 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);
Upvotes: 2