function n = countPattern(P, A)
%COUNTPATTERN Count occurrences of a pattern in a matrix.
%   n = countPattern(P, I) returns the number of times
%   a pattern P appears in a matrix A.

[pRows, pCols] = size(P);
[aRows, aCols] = size(A);
n = 0;

for r = 1:(aRows - pRows + 1)
    for c = 1:(aCols - pCols + 1)
        % get part of A that overlaps with P
        B = A(r:(r + pRows - 1), c:(c + pCols - 1));
        if all(P == B)
            n = n + 1;
        end
    end
end


