0

I have a 5x5 matrix and I have to find the minimum of adjacent elements for a position and add that minimum number to that position... this has to be done for all the elements in the matrix except for the 1st row and 1st column. This is the matrix A= [[1 1 2 2 3],[1 1 0 1 0],[2 0 1 0 1],[3 2 1 2 1],[4 0 1 0 1]]

  • 1
    Welcome. This might help you. https://stackoverflow.com/questions/15799261/numpy-fast-calculations-considering-items-neighbors-and-their-position-inside Afterwords just devide your array by the newly defined one. It seems to be a little over the top, but will do the job – Tom S May 03 '21 at 10:24
  • I've tried that one It doesn't work out – pruthvi sushanth May 03 '21 at 11:44
  • Can you post your code from your try so I can figure out, where the problem lies? I do want to safe the time and not implement it myself. In general this shoud do the trick. – Tom S May 03 '21 at 12:55
  • it's a big code actually can you share your mail id? i'll mail the code directly to you – pruthvi sushanth May 03 '21 at 13:03
  • By adjacent, do you mean only the ones above, below, to the left and right or do you mean the ones that are diagonally adjacent too? – yann ziselman May 05 '21 at 09:52
  • all of them left, right,, top, bottom, diagonal elements also included – pruthvi sushanth May 10 '21 at 05:08

1 Answers1

0

import numpy as np

a = [1,2,1,3,1] b = [2,1,2,1,2]

First Matrix

def get_matrix1(a,b): d = [] for x in a: for y in b: d.append(abs(y-x))
return np.reshape(d,(5,5))

Second Matrix

def get_matrix2():

# Matrix 
m1 = get_matrix1(a,b)
print('First Matrix : {}'.format(m1))

# Cumulative Addition
m1[0] = np.cumsum(m1[0])
m1[:,0] = np.cumsum(m1[:,0])
m2 = m1.copy()
print('\nCumulative Addition Matrix : {}'.format(m2))

# Second Matrix
i_rows,j_cols = [0,1,2,3],[0,1,2,3]
edge_rows,edge_cols = [1,2,3,4],[1,2,3,4]

for i,row in zip(i_rows, edge_rows):
    for j,col in zip(j_cols, edge_cols):

        # old
        old = m2[row,col]
        print('\nOld : {}'.format(old))
        
        # edges 
        c,u,l = m2[i,j],m2[i,j+1],m2[i+1,j]
        r = (c,u,l)
        print('Edges : {}'.format(r))
        
        # new
        new = min(r) + old
        print('New : {}'.format(new))
        
        # update
        m2[row,col] = new
        print('Updated Matrix :')
        print(m2)
        

get_matrix2()