MATLAB: How to write a code to find the position of a smaller (m x n) matrix in a big (M X N) matrix

matrix

how to write a code in matlab to find the position of a smaller (m x n) matrix in a big (M X N) matrix ?

Best Answer

>> A = [ 102 69 101 5 82 103 96 95 120
114 120 18 107 22 87 100 35 43
16 121 53 117 89 40 24 85 74
115 20 115 85 4 119 62 82 28
80 122 100 95 35 5 56 21 94
13 120 120 93 6 55 81 15 32
35 61 82 50 13 48 89 63 64];
>> a = [120 18;
121 53;
20 115];
>> conv2(A,rot90(1./a,2),'valid') == numel(a);
or for MATLAB >= R2016b
[m,n] = size(A);
[q,w] = size(a);
r = reshape(1:numel(A),m,[]);
p = reshape((0:q-1)' + (0:w-1)*m,1,[]);
r = r(1:m-q+1,1:n-w+1);
out = r(ismembertol(A(r(:) + p),a(:)',1e-5,'ByRows',1,'DataScale',1));
for other versions of the MATLAB
[m,n] = size(A);
[q,w] = size(a);
r = reshape(1:numel(A),m,[]);
p = reshape(bsxfun(@plus,(0:q-1)',(0:w-1)*m),1,[]);
r = r(1:m-q+1,1:n-w+1);
out = r(ismembertol(A(bsxfun(@plus,r(:),p)),a(:)',1e-5,'ByRows',1,'DataScale',1));