Robochameleon  v1.0
sumbitxor.m
1 function s = sumbitxor(a,b)
2 
3  if ~isvector(a) || ~isvector(b)
4  roboerror('wrongInput','Both inputs must be vectors');
5  end
6 
7  a = parseinput(a);
8  b = parseinput(b);
9 
10  L = numel(a)-numel(b);
11  if L<0
12  [b,a] = deal(a,b); % swap variables in place
13  L = -L;
14  end
15 
16  nomem = warning('error','MATLAB:nomem'); %#ok<CTPCT> Change error to warning
17  try
18  s = uint32(xcorr(double(a),double(~b),L))+uint32(xcorr(double(~a),double(b),L));
19  s = s(L+1:end);
20  catch exception
21  warning(nomem); % re-enable as error
22  switch exception.identifier
23  case nomem.identifier
24  a = logical(a);
25  b = logical(b);
26  N = numel(b);
27 
28  s = zeros(L+1,1,'uint32');
29  for ptr=0:L
30  s(ptr) = nnz(xor(a(ptr+(1:N)),b));
31  end
32  otherwise
33  rethrow(exception);
34  end
35  end
36 
37 end
38 
39 
40 
41 function x = parseinput(x)
42  if ~isvector(x)
43  roboerror('wrongInput','Both inputs must be vectors');
44  elseif ~islogical(x)
45  if ~isnumeric(x) || ~all(x==0 | x==1)
46  roboerror('wrongInput','Input must be a numeric vector with zeros or ones only.');
47  elseif verLessThan('matlab', '8.4.0') % Trick to save memory
48  % Before MATLAB R2014b, input to xcorr must be double
49  x = double(x);
50  else
51  % Since MATLAB R2014b, input to xcorr can be uint8
52  x = uint8(x);
53  end
54  end
55  x = x(:);
56 end