0

Just ran into this fun problem but I can't figure it out correctly

You have a matrix:

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

and your given two coordinates:

(1,1) and  (2,2) 

find the corresponding submatrix:

so (1,1) and (2,2)

will create

|5 6|
|8 9| 

my code:

def get_submatrix(matrix, coor):
    m = len(matrix)

    #chooses what rows
    lstart = coor[0][0]
    lend = coor[1][0]

    #chooses what columns
    estart = coor[0][1]
    eend = coor[1][1]
    subgrid = []
    print('coors: (%s, %s), (%s, %s) ' % (lstart, estart, lend, eend))
    #iterate through the matrices
    for i in range(lstart,lend+1):
    #    print('matrix index: %s' % i)
        print('matrix: %s' % matrix[i])
        row = matrix[i]
        subgrid.append(row[estart:len(row)])
        print('subgrid: %s' % subgrid)
    return subgrid

My code uses len(row) to pull the end of the row. which might work for some cases but not all cases. Any help on crafting the for loop to obtain the submatrix?

Kyle Calica-St
  • 2,629
  • 4
  • 26
  • 56
  • 1
    how is this a summation of anything? – sam-pyt Dec 11 '17 at 21:42
  • What *theorem*? – Willem Van Onsem Dec 11 '17 at 21:43
  • not suppose to be a summation, i thought i cleared all references from that before publishing. just trying to get the submatrix using the two coordinates. – Kyle Calica-St Dec 11 '17 at 22:18
  • Don't do this to yourself. Libs like `numpy` were written (also) to avoid brutal index massacres like this... have a look here https://stackoverflow.com/questions/4257394/slicing-of-a-numpy-2d-array-or-how-do-i-extract-an-mxm-submatrix-from-an-nxn-ar – Omni Dec 11 '17 at 22:46
  • usually i agree but this was pulled from an interview question i had. libraries not allowed. if this was for some project and i asked on stackoverflow that would be fine. but this was posted for better logical thinking. i need more than just a library. – Kyle Calica-St Dec 12 '17 at 02:31

0 Answers0