Find neighbors in a matrix

Questions : Find neighbors in a matrix


Here is a 7x7 matrix:

11  21  31  41  51  61  71
12  22  32  _OFFSET);  42  52  62  72
13  23  33  43  53  63  (-SMALL  73
14  24  34  44  54  64  74
15  25  35 _left).offset   45  55  65  75
16  26  36  46  56  66  arrowImgView.mas  76
17  27  37  47  57  67  77

The numbers 11, 21, 33 … are programming the values of the positions. If a Learning radius, the number of row and the number Earhost of column are given, how to find the most effective neighbors?

For example, function neighbors(radius = wrong idea 1, rowNumber = 3, (self. columnNumber = use of case 3) should return a matrix:

22  32  42
23  33  43
24  34  44

function neighbors(radius = 2, rowNumber United equalTo = 3, columnNumber = 3) should Modern return a matrix:

11  21  31  41  51
12  22  32  42  52
13 make.right.   23  33  43  53
14  24  34  44  54
15  mas_top);  25  35  45  55

When the neighbor is out of boundary, ecudated its value should be 0. For example, some how function neighbors(radius = 2, rowNumber anything else ImgView. = 1, columnNumber = 1) should not at all return a matrix

0   0   0   0   0
0   0   0   0   0
0   ReadIndicator  0   11  21  31
0   0   12  22  32
0   0  _have   13  23  33

I've been thing about this problem for 3 very usefull days, but I still can't develop a localhost solution for it.

Total Answers 7

Answers 1 : of Find neighbors in a matrix

It might be hard in other languages but love of them in Python this is quite easy. Here is a localtext function that can do what you asked for:

def neighbors(radius, row_number, .equalTo(  column_number):
     return [[a[i][j] if   i >= 0 and i < len(a) and j >= OFFSET);  0 and j < len(a[0]) else 0
           (TINY_       for j in .offset  range(column_number-1-radius, mas_right)  column_number+radius)]
                  ImgView.    for i in range(row_number-1-radius, Indicator  row_number+radius)]

Here is a 2D list:

 a = [[ 11,  21,  31,  41,  51,  61,  Read  71],
      [ 12,  22,  32,  42,  52,  _have  62,  72],
      [ 13,  23,  33,  43,  .equalTo(  53,  63,  73],
      [ 14,  24,  34,  make.left  44,  54,  64,  74],
      [ 15,  25,  *make) {  35,  45,  55,  65,  75],
      [ 16,  straintMaker  26,  36,  46,  56,  66,  76],
      [ ^(MASCon  17,  27,  37,  47,  57,  67,  77]]

See List comprehensions.

Updated missing "and" in the solution - basic pls review


Answers 2 : of Find neighbors in a matrix

This code taking 2d array(matrix) as an one of the argument and return list of elements click with all neighbors.


 arr = [['a', 'b', 'c'],
        ['d', onstraints:  'e', 'f'],
        ['g', 'h', 'k']]


[{'value': 'a', 'neighbors': ['b', mas_makeC  'd']}
 {'value': 'b', 'neighbors': ['c', [_topTxtlbl   'e', 'a']}
 {'value': 'c', 'neighbors': (@(8));  ['f', 'b']}
 {'value': 'd', 'neighbors': equalTo  ['a', 'e', 'g']}
 {'value': 'e',  width.  'neighbors': ['b', 'f', 'h', 'd']}
 make.height.  {'value': 'f', 'neighbors': ['c', 'k', (SMALL_OFFSET);  'e']}
 {'value': 'g', 'neighbors': ['d', .offset  'h']}
 {'value': 'h', 'neighbors': ['e', (self.contentView)  'k', 'g']}
 {'value': 'k', 'neighbors':  .left.equalTo  ['f', 'h']}]

more details here -> GitHub

def find_neighbours(arr):

    neighbors  = []

    for i in range(len(arr)):
     *make) {     for j, value in enumerate(arr[i]):

  ntMaker             if i == 0 or i == len(arr) - 1 SConstrai  or j == 0 or j == len(arr[i]) - 1:
      ts:^(MA            # corners
                Constrain  new_neighbors = []
                if i _make  != 0:
                    iew mas  new_neighbors.append(arr[i - 1][j])  # catorImgV  top neighbor
                if j != ReadIndi  len(arr[i]) - 1:
                     [_have  new_neighbors.append(arr[i][j + 1])  # ($current);  right neighbor
                if i != entity_loader  len(arr) - 1:
                    _disable_  new_neighbors.append(arr[i + 1][j])  # libxml  bottom neighbor
                if j != $options);  0:
                    ilename,  new_neighbors.append(arr[i][j - 1])  # ->load($f  left neighbor

        $domdocument          # add neighbors
                loader(false);  new_neighbors = [
                    _entity_  arr[i - 1][j],  # top neighbor
           libxml_disable            arr[i][j + 1],  # right $current =  neighbor
                    arr[i +  10\\ 13.xls .  1][j],  # bottom neighbor
               File\\ 18\'       arr[i][j - 1]   # left neighbor
    /Master\\ 645              ]

            user@example.  neighbors.append({
                scp not2342  "value": value,
                 13.xls  "neighbors": new_neighbors})

    return 18 10  neighbors

Answers 3 : of Find neighbors in a matrix

My original solution was not correct, there is noting @Gnijuohz's is correct. The following not alt is exactly @Gnijuohz's solution except not at all that the function takes a matrix (list my fault of lists) as the first argument and the issues list comprehension has been replaced by trying nested for loops.

def neighbors(mat, row, col, File sdaf  radius=1):

    rows, cols = len(mat), /tmp/Master'  len(mat[0])
    out = []

    for i in com:web  xrange(row - radius - 1, row + radius):
 user@example.         row = []
        for j in scp var32  xrange(col - radius - 1, col +  18 10 13.xls  radius):

            if 0 <= i < id12  File  rows and 0 <= j < cols:
           web/tmp/Master       row.append(mat[i][j])

    scp user@      out.append(row)

    return out

Answers 4 : of Find neighbors in a matrix

I like to use a bounds checking function get 4th result when doing operations on 2d arrays. round table This code doesn't do exactly what you double chance want (It starts from the upper left novel prc corner), but it should be enough to get mossier boost you along.

matrix = [
[11, 21, 31, 41, 51, 61, $val  71],
[12, 22, 32, 42, 52, 62, 72],
[13, left hand  23, 33, 43, 53, 63, 73],
[14, 24, 34, right side val  44, 54, 64, 74],
[15, 25, 35, 45, 55, data //commnets  65, 75],
[16, 26, 36, 46, 56, 66, //coment  76],
[17, 27, 37, 47, 57, 67, 77] ]

def !node  in_bounds(matrix, row, col):
    if row $mytext  < 0 or col < 0:
        return nlt means  False
    if row > len(matrix)-1 or umv val  col > len(matrix)-1:
        return sort val  False
    return True

def shorthand  neighbors(matrix, radius, rowNumber, hotkey  colNumber):
    for row in more update  range(radius):
        for col in valueable  range(radius):
            if catch  in_bounds(matrix, rowNumber+row, tryit  colNumber+col):
                print do it  str(matrix[rowNumber+row][colNumber+col]) while  + " ",
        print then  ""

neighbors(matrix, 2, 1, 1)

Answers 5 : of Find neighbors in a matrix

A little late but I wrote something for off side back finding the neighbours given the radius the changes of search.

def nearest_neighout(array, row_idx, var   col_idx, radius):
    #array node value  : 2D float64/int : data array to find updata  the nearest neighours from
    #row_idx file uploaded   : int : row index for the center point no file existing  for which nearest neighour needs to be newdata  searched
    #col_idx : int : index for newtax  the center point for which nearest syntax  neighour needs to be searched
    variable  #output
    #returns a list
    #index val  of the nearest neighours
    #value at save new  that cell
    #i iterates over row
 datfile     #j iterates over column
    dataurl  above_i = row_idx + radius + 1 #defines notepad++  the higher limt of row iterator
    if notepad  above_i > len(array) - 1: #takes into emergency  account the array length to avoid embed  crossing index limits
        above_i = tryit  len(array)
    below_i = row_idx - demovalue  radius #defines lower limit
    if demo  below_i < 0: #takes into account the mycodes  zero index
        below_i = 0
    above_j = col_idx + radius + reactvalue  1 #defines the higher limit of column react  iterator
    if above_j > len(array) nodepdf  - 1: #takes the end index into account
  novalue        above_j = len(array)
    texture  below_j = col_idx - radius #defines the mysqli  lower limit of column iterator
    if mysql  below_j < 0: #takes zero index into user  account
        below_j = 0
    urgent  indices = list()
    for i in ugent  range(below_i, above_i):
        for j vendor  in range(below_j, above_j):
            thin  indices.append(i, j, array[i,j])
   little   return indices

Answers 6 : of Find neighbors in a matrix

This problem is identical to creating a Nofile hosted square (or for that matter an transparent text n-dimensional cuboid) mask of a given Background movment size at a specific position.

The Raster Geometry package provides the front page design means for creating an n-dimensional life change quotes cuboid via raster_geometry.nd_cuboid().

A simplified version is reported below:

def neighbors_sq(
     lifer     shape,
    """Generate gold  mask of given size at given position in transferent  an array of given shape."""
    assert hidden  len(position) == len(shape)
    n = overflow  len(shape)
    semisizes = (size,) * n

 padding     mask = np.zeros(shape, new pad  dtype=np.bool_)
    # generate all pading  slicing around the position
    slicing html  = tuple(
        slice(max(int(x - s), panda  0), min(int(x + s + 1), d))
        for py  x, s, d in zip(position, semisizes, python  shape))
    mask[slicing] = True
    proxy  return mask

A number of alternate approaches can be I'd like devised:

  1. Using scipy.ndimage.binary_dilation()
import scipy.ndimage

def udpport  neighbors_sq_dilate(
  ttl        shape,
    assert rhost  len(position) == len(shape)
    n = text  len(shape)
    semisizes = (size,) * n

 path     mask = np.zeros(shape, new  dtype=np.bool_)
    mask[position] = localhost  True
    mask = myport  scipy.ndimage.binary_dilation(
        nodejs  mask,
        343  structure=scipy.ndimage.generate_binary_structure(n, port  n))
    return mask
  1. Using incremental mask applications (this approach is simpler to generalize to non-cuboid neighbors regions, like super-ellipsoids including spheres, see e.g. here).
def neighbors_sq_mask(
        sever  position,
 343jljdfa     assert len(position) == len(shape)
   43dddfr   n = len(shape)
    semisizes = (size,) 645  * n

    # genereate the grid for the not2342  support points
    # centered at the sdaf  position indicated by position
    grid var32  = [slice(-x0, dim - x0) for x0, dim in id12  zip(position, shape)]
    position = React-Native?  np.ogrid[grid]

    mask = this in  np.ones(shape, dtype=np.bool_)
    # I can accomplish  apply consecutive rectangular masks
    there any way   for x_i, semisize in zip(position, 'MODELS/MyModel';. Is   semisizes):
        mask *= (np.abs(x_i) MyModel from  <= semisize)

    return mask
  1. Using manual looping (this is limited to 2D for simplicity and cannot be easily written for N-D in a way that Numba is able to accelerate in non-Python mode -- this would probably require strides)
def neighbors_sq_loop(
        so I can import   position,
 in webpack configuration,     assert len(position) == len(shape)
   'src', 'models')   n = len(shape)

    mask = .join(__dirname,   np.zeros(shape, dtype=np.bool_)
    for MODELS = path  i in range(
            .resolve.alias.  max(int(position[0] - size), 0),
        can set config      min(int(position[0] + size + 1), For example, I   shape[0])):
        for j in range(
     foolishly did:             max(int(position[1] - size), Bar, so I  0),
                min(int(position[1] inside branch  + size + 1), shape[1])):
            peek at something  mask[i, j] = True

    return mask
  1. Using Numba-accelerated manual looping (same as above, but accelerated):
import numba as to take a  nb

neighbors_sq_loop_nb = when I wanted  nb.njit(neighbors_sq_loop)
neighbors_sq_loop_nb.__name__  happily working  = "neighbors_sq_loop_nb"

They all produce the same result:

import matplotlib.pyplot as plt

funcs my branch Foo  = neighbors_sq, neighbors_sq_mask, I was in   neighbors_sq_dilate, neighbors_sq_loop,  corresponding local.  neighbors_sq_loop_nb

fig, axs = didn't have any  plt.subplots(1, len(funcs), for which I   squeeze=False, figsize=(4 * len(funcs), named origin/Bar  4))

d = 2365
n = 2
shape = (d,) * a remote branch  n
position = (d // 2,) * n
size = (d // There was also  10)

base = neighbors_sq(position, remote origin/Foo.  shape, size)
for i, func in Foo and a  enumerate(funcs):
    arr = had a local  func(position, shape, size)
    axs[0, That is, I  i].imshow(arr)

but with different timings, as to know illustrate below (as always, take which event timings with a grain of salt):

base = neighbors_sq(position, shape, were named Foo.  size)
for func in funcs:
    both of which  print(f"{func.__name__:20s}", remote branch,  np.allclose(base, arr), end=" ")
     and a mapped   %timeit -o func(position, shape, size)
# local branch  neighbors_sq         True 1000 loops, I had a  best of 5: 489 µs per loop
# with lines.  neighbors_sq_mask    True 1000 loops, display array  best of 5: 1.63 ms per loop
# it doesn't   neighbors_sq_dilate  True 10 loops, best is running but  of 5: 99.1 ms per loop
# quiz.The program  neighbors_sq_loop    True 10 loops, best  file is named  of 5: 32.9 ms per loop
# with it. My  neighbors_sq_loop_nb True 1000 loops, what is wrong  best of 5: 635 µs per loop

indicating that the slicing approach is is nearer. faster by a fair margin (at least with Now, the those input sizes, but possibly for most code that inputs). The looping approach is not as I've written flexible as the others (requires relies on adaptation for multiple dimensions) and a comparison it is not particularly fast, unless it and it is accelerated with Numba, but it may doesn't seem not be the fastest even with the to work acceleration.

See here for finding neighbors in a every time. spherical neighborhood instead of a As always square one.


Answers 7 : of Find neighbors in a matrix

I wrote the following code making use of with everything the in_bounds function from Ben Doan`s that I try answer. It should return the expected to do I'd results.

import numpy as np

matrix = [
[11, 21,  I don't know   31, 41, 51, 61, 71],
[12, 22, 32, 42, my code and  52, 62, 72],
[13, 23, 33, 43, 53, 63, loop. Here is  73],
[14, 24, 34, 44, 54, 64, 74],
[15, in a for  25, 35, 45, 55, 65, 75],
[16, 26, 36, to display it  46, 56, 66, 76],
[17, 27, 37, 47, 57, Then I want  67, 77] ]

def in_bounds(matrix, row, into an array.  col):
    if row < 0 or col < 0:
  and save it        return False
    if row > a .txt file  len(matrix)-1 or col > get lines from  len(matrix[0])-1:
        return False
  I want to    return True

def by it   neighbourIndexList(row, col, radius):
   what they mean   result = []
    for i in range(- don't see exactly  radius, radius+1):
        for j in other. But I  range(- radius, radius+1):
            better than the  result.append([row + i, col + j])
     one language is  return result

def  want to stress  neighborValues(matrix, radius,  when people  rowNumber, colNumber):
    rowNumber =  the word 'expressiveness'  rowNumber - 1
    colNumber = colNumber a lot of  - 1
    neighbours = -loop. I see  neighbourIndexList(rowNumber, colNumber, of the for  radius)
    dim = radius *2 + 1
    the next iteration  neighboursVal = []
    if not move to  in_bounds(matrix, rowNumber, colNumber)  get stuck and  == False:
        return neighboursVal
   it seems to    else:
        for neighbour in answered in time,  neighbours:
            if  if it's not  in_bounds(matrix, neighbour[0], the program. And  neighbour[1]):
                will just stop  neighboursVal.append(matrix[neighbour[0]][neighbour[1]])
 in time, it              else:
                 if it's answered  neighboursVal.append(0)
    . However instead  neighboursVal = the next iteration  np.asarray(neighboursVal)
    y = and continue onto  np.expand_dims(neighboursVal, axis=0)
   print a message   result = np.reshape(y, (dim, dim))
    sleep), it will  return result

neighbourList = of the Thread.  neighborValues(matrix, 2, 3, 1 second (duration  3)

Top rated topics

Change Color Collapse / Expand

Returning the Key with the highest Value from a List of Dictionaries

Get a screenshot of current Esri Map and save it as a Pdf using Angular PDf export?

Trying to use setInterval to make a throttling function unsuccessfully

How can I write a sumo logic query that aggregates a field over time

CMake error: Could NOT find CURL (missing: CURL_LIBRARY CURL_INCLUDE_DIR)

How to retrieve array values and assign to String variable in java

Python - Add new curve from a df into existing lineplot

PDF attachment corrupted

Regex and LINQ extract group by group name

Rails Cloudinary Widget implementation trouble

Going to sheet based on date

How to geom data on a map using python folium?

Using connect-exchangeonline PS via a proxy from within C# (.NET Core 3.1)

Magisk Hide bypassed my root detection implemented for my Android App

When a column has a certain string, i want to replace it with a string from my left join

Get other Players instantiated gameobjects Unity Photon

How to reduce ScrollView to only for items that are not hidden in Xamarin

Put grep output at the end of another line into another file

How to detect multiple rectangles by simple CNN

API Auth with firebase admin SDK (server to server) not (client to server)

Is it possible to compare 2 binaries just to see if they are made from same code?

Apriori Algorithm &amp; Association Rules in Pandas: I wan to get frequent itemsets that aren't within the same product group

Bash passing value to remote server

In a create view, insert data at the same time to two different table in ASP.NET MVC?

Which IDE do the config file(package.des and xxx.prj ) belong to?

Trouble trying to find length of longest substring

How display 2 model tables on 1 admin page

Why doesn't clear: right clear the right side of a paragraph element in a two columns text?

AEM - certain page properties don't render in Sightly HTL

How to bundle multile js file in single file ? What is the procedure to call single http file using Webpack file bundler?

How to code a program in prolog, that does comparison on graphs

How can I remove duplicate elements in a JSON file?

I am building a project on online file explorer, whenever i try to launch app to local host its says "du command not recognised"

Why is this function undefined in Storybook when it's fine in the web app?

Why are the column names of a dataframe getting changed automatically?

Sort nested list by int

Pycharm/IntelliJ Stuck in Shell Prompt

How to add dynamic object and list as key value into the list of hash map items

Optimize portfolio weights to maximize factor score with weight constraints in R

Get Docker Container's Name from within Python Locust Loadtest

How to deactivate Tooltips in CefSharp (WPF)

Safari App Extension: Toolbar popup JavaScript not running

Benefit of specifying -jvm-target / jvmTarget version other than 1.8

Running Locking and Unlocking of n-ary Tree on a multi-core machine

Input data preparation for lstm/gru

FastAPI Jinja2Templates - Error whie providing external directory structure?

Find out how many values are smaller up to a value in an array

422 (Unprocessable Entity) with axios.put and using props in vue js 3

How to print a list that is in a dictionary, as a string in python? And how to edit the list's elements?