Auxiliary method to translate a (row,col) pair into a linear index

50 Views Asked by At

I don’t understand the meaning of the linind part of the code. Can someone explain it?

class SqMatrix:
    def __init__(self, n):
        self.l = [0 for i in range(n**2)]
        self.n = n

    def linind(self, row, col):
        return self.n * row + col
1

There are 1 best solutions below

0
On

I am not a python guy but from what I understand this is simply multiplying the given row index by the matrix dimension and adding the column index.

If row count starts with $0$, "row" (counted from 0) would actually index in the "row+1" row (counted from 1). So there are in fact "row" complete rows in the matrix before reaching the one that is being indexed.

Now one would only need to add "col" to receive the linear index (starting with 0) for the element at (row, col).

Note that all indices (row, col, linear) start with 0.