Robochameleon  v1.0
count_binary_runs.m
1 function [counts0,counts1] = count_binary_runs(x)
2 
3 if ~isvector(x) || ~islogical(x)
4  error('Input must be a logical vector.');
5 end
6 
7 N_max = ceil(numel(x)/2);
8 counts0 = nan(N_max,1);
9 counts1 = nan(N_max,1);
10 idx_0 = 0;
11 idx_1 = 0;
12 
13 x(end+1) = ~x(end); % Append one different bit to count correctly the last run
14 current = x(1);
15 idx = 1;
16 for i=2:numel(x);
17  if x(i)~=current % new bit is flipped => append new run
18  if current % if was 1
19  idx_1 = idx_1+1;
20  counts1(idx_1) = i-idx;
21  else
22  idx_0 = idx_0+1;
23  counts0(idx_0) = i-idx;
24  end
25  current = ~current;
26  idx = i;
27  end
28 end
29 
30 counts0 = counts0(1:idx_0);
31 counts1 = counts1(1:idx_1);