-2

Having a matrix which looks like this

9 9 1 9 9 9 9 1
9 9 1 9 9 9 9 9
9 9 9 9 9 9 9 9
9 9 1 9 9 9 9 9
9 9 9 9 9 1 1 1
9 9 9 9 9 1 9 9
9 9 9 1 9 9 9 9
9 9 1 9 1 9 9 9

I would like to detect for each position in the matrix, if there is at least a value 1 sorrounding the matrix in question such that for element in {2, 2} i want to check values in {1,1}, {1,2}, {1,3}, {2,1}, {2,3}, {3,1}, {3,2}, {3,3} and if any position mentioned contains 1, then i store the element in {2,2} in a seperate variable.

I do not know how to get by this and would like to know if there is any pythonic function or way that can do this?

  • [i downvoted your question because](http://idownvotedbecau.se/noattempt/) you do not show any effort you made. – hiro protagonist Apr 24 '18 at 12:07
  • I really have no idea how to do it and I need some assistance that is why I posted this – user3185171 Apr 24 '18 at 12:09
  • 1
    Here are a couple of posts to get you started: https://stackoverflow.com/q/13621651/1288 https://codereview.stackexchange.com/q/178603/2105 Also, neighbor checking is a big component of Conway's Game of Life. You might check different implementations of that to see how it's done. – Bill the Lizard Apr 24 '18 at 12:11

2 Answers2

3

You can take inspiration from this question and use conv2

In MATLAB (you said "pythonic" but tagged MATLAB) this looks like the following:

numneighbours = conv2( A==1, [1 1 1; 1 0 1; 1 1 1], 'same' );

Now you want any elements where numneighbours > 0

output = A(numneighbours > 0);

This could of course be done in 1 line.


This answer suggests convolve2d is a Python equivalent to MATLAB's conv2.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
1

A possible solution is dilating a mask which indicates where the one values are, with a square 3x3 structuring element, as follows:

onesMask = mat==1;
res = imdilate(mask,strel('square',3)) & ~onesMask;

result:

 0     1     0     1     0     0     1     0
 0     1     0     1     0     0     1     1
 0     1     1     1     0     0     0     0
 0     1     0     1     1     1     1     1
 0     1     1     1     1     0     0     0
 0     0     1     1     1     0     1     1
 0     1     1     0     1     1     1     0
 0     1     0     1     0     1     0     0
ibezito
  • 5,782
  • 2
  • 22
  • 46