MATLAB: How to search a binary array inside other bigger binary array

findmatrix array

For example I have the A array
A = [1 0 0 1 0,0 0 0 0 0,0 1 0 1 0,0 0 0 0 0]
I need to seach how many times is the B array in A.
B = [1 0,0 0]

Best Answer

A = [1 0 0 1 0;0 0 0 0 0;0 1 0 1 0;0 0 0 0 0]
B = [1 0;0 0]
Embed A into a larger matrix of nans because nlfilter sets boundary values to 0; the following code is just valid for 2x2 matrices B
A2 = nan(size(A)+2))
A2(2:end-1, 2:end-1) = A;
nnz(nlfilter(A2, [2 2], @(x) (isequal(x,B))))
Related Question