DianaLog
DianaLog

Reputation: 336

matlab get neighbours on matrix

I have a simple matrix:

1  2  3  4
5  6  7  8
8  9  10 11
12 13 14 15

I need to loop through each element and build a new matrix with 3 of its surrounding elements (the one to the right, bottom right and bottom). So I will end up with an array like so:

1  2  6  5
2  3  7  6
3  4  8  7

I managed to do this but when I need to jump to the row below I can't seem to figure out how to do it. for the next row it should be:

5  6  9  8
6  7  10 9 
...

Any ideas?

Upvotes: 3

Views: 234

Answers (2)

Divakar
Divakar

Reputation: 221504

My favourite bsxfun being put to work here -

[M,N] = size(A); %// A is Input
ind =  bsxfun(@plus,[1:M-1],[(0:N-2).*M]') %//'
out = A(bsxfun(@plus,ind(:),[0 M M+1 1]))  %// Desired output

Output using the sample input from question -

out =
     1     2     6     5
     2     3     7     6
     3     4     8     7
     5     6     9     8
     6     7    10     9
     7     8    11    10
     8     9    13    12
     9    10    14    13
    10    11    15    14

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

[m n] = size(A);
[jj ii] = ndgrid(1:m-1, 1:n-1); %// rows and columns except last ones
kk = sub2ind([m n], ii(:),jj(:)); %// to linear index
B = [ A(kk) A(kk+m) A(kk+m+1) A(kk+1) ] %// pick desired values with linear index

In your example:

B =
     1     2     6     5
     2     3     7     6
     3     4     8     7
     5     6     9     8
     6     7    10     9
     7     8    11    10
     8     9    13    12
     9    10    14    13
    10    11    15    14

Upvotes: 4

Related Questions