简体   繁体   中英

Get matrix index from array index

I am trying to get a matrix index from an array index

Example: I have a 3*2 matrix

a b

c d

e f

which as array can be written as [a,b,c,d,e,f] .

From the position of element in array say 5th, I want to get the position in matrix which in this case is 3*1

Please Help!

Use integer division and remainder

row = i // width
col = i % width
def GetRowAndColum(iNoOfRows,  iNoOfColumn, iIndex):
        #Floor division to get row
        iRowInMatrix = iIndex//iNoOfColumn
        iColumnInMatrix = iIndex % iNoOfColumn
        return iRowInMatrix, iColumnInMatrix


mat = ['a', 'b', 'c', 'd', 'e', 'f']
iNoOfColumn = 2
iNoOfRows = 3

iIndex = 5
i, j = GetRowAndColum(iNoOfRows, iNoOfColumn, iIndex)
print "Row in matrix: ", i
print "Column in matrix: ", j

OutPut:

[Tryouts]$ python TestMat.py Row in matrix: 2 Column in matrix: 1

I have assumed matrix with zero based index. If your index starts with 1 then simply add 1 to row and column index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM