python - Matrix of labels to adjacency matrix -



python - Matrix of labels to adjacency matrix -

just wondering if there off-the-shelf function perform next operation; given matrix x, holding labels (that can assumed integer numbers 0-to-n) in each entry e.g.:

x = [[0 1 1 2 2 3 3 3], [0 1 1 2 2 3 3 4], [0 1 5 5 5 5 3 4]]

i want adjacency matrix g i.e. g[i,j] = 1 if i,j adjacent in x , 0 otherwise.

for illustration g[1,2] = 1, because 1,2 adjacent in (x[0,2],x[0,3]), (x[1,2],x[1,3]) etc..

the naive solution loop through entries , check neighbors, i'd rather avoid loops performance reason.

you can utilize fancy indexing assign values of g straight x array:

import numpy np x = np.array([[0,1,1,2,2,3,3,3], [0,1,1,2,2,3,3,4], [0,1,5,5,5,5,3,4]]) g = np.zeros([x.max() + 1]*2) # left-right pairs g[x[:, :-1], x[:, 1:]] = 1 # right-left pairs g[x[:, 1:], x[:, :-1]] = 1 # top-bottom pairs g[x[:-1, :], x[1:, :]] = 1 # bottom-top pairs g[x[1:, :], x[:-1, :]] = 1 print(g) #array([[ 1., 1., 0., 0., 0., 0.], # [ 1., 1., 1., 0., 0., 1.], # [ 0., 1., 1., 1., 0., 1.], # [ 0., 0., 1., 1., 1., 1.], # [ 0., 0., 0., 1., 1., 0.], # [ 0., 1., 1., 1., 0., 1.]])

python numpy matrix graph adjacency-matrix

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -