Benchmark between rahnema1 and m7913d
Horizontal and vertical matches
Benchmarking the solution of rahnema1 and m7913d using timeit for the given example (Small A) and one that is 100^2 larger (Large A), gives the following results:
Method | Small A | Large A
--------------------------------
rahnema1 | 4.0416e-05 | 0.0187
m7913d | 2.5242e-05 | 0.0129
Note that m7913d's solution is ~50% faster.
Horizontal (or vertical) matches only
If you are only interested in horizontal matches, the following results are obtained:
Method | Small A | Large A
--------------------------------
rahnema1 | 9.6752e-06 | 0.0115
m7913d | 5.8634e-06 | 0.0056
In this case, m7913d's solution is even more favorable, being up to ~100% faster.
Complete benchmark code
A=[56 55 53 52 53;
49 45 44 45 47;
33 30 31 34 35;
34 34 27 24 26;
44 48 45 35 24;
56 57 57 53 39;
62 62 62 60 55;
62 61 61 54 47;
49 47 42 40 32;
47 42 44 45 40];
B=[34 27 24];
A_large = repmat(A, 100, 100);
t_m7913d = timeit(@() m7913d(A, B))
t_rahnema = timeit(@() rahnema1(A, B))
t_large_m7913d = timeit(@() m7913d(A_large, B))
t_large_rahnema = timeit(@() rahnema1(A_large, B))
function [row_h, col_h, row_v, col_v] = m7913d(A, B)
Ah = true(size(A) - [0 length(B)-1]);
Av = true(size(A) - [length(B)-1 0]);
for i=1:length(B)
Ah= Ah & A(:, i:end-3+i) == B(i);
Av= Av & A(i:end-3+i, :) == B(i);
end
[row_h, col_h] = find(Ah);
[row_v, col_v] = find(Av);
end
function [row_h, col_h, row_v, col_v] = rahnema1(A, B)
n = numel(B);
C = A == reshape(B,1,1,n);
mask_h = permute(eye(n),[3 2 1]);
mask_v = permute(eye(n),[1 3 2]);
[row_h, col_h]=find(convn(C,mask_h,'valid')==n);
[row_v, col_v]=find(convn(C,mask_v,'valid')==n);
end