I was following this stackoverflow post on csr matrix multiplication to a vector and Implement it in python and getting list out of range error.
Here is my code:
def MatrixMultiplication(data,row_ptr,col_ptr,vec):
ResultMatrix =[]
vec_len = len(vec)
for i in range(0,vec_len):
ResultMatrix.insert(i,0)
for i in range(0,vec_len):
start, end = row_ptr[i], row_ptr[i + 1]
for k in range(start, end):
ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]
return ResultMatrix
data = [2, 4, 7, 1, 3, 2]
row_ptr = [2,3 ,5, 5 ,6]
col_ptr = [1 ,3, 4, 0, 3, 3]
vec = [2,3, 5, 4, 2]
MatrixMultiplication(data,row_ptr,col_ptr,vec)
Please help me out where I am going wrong .
Output should be: [ 22 14 14 0 8]
Error :
IndexError: list index out of range
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<command-338158343473691> in <module>()
----> 1 MatrixMultiplication(data,row_ptr,col_ptr,vec)
<command-3658506804172571> in MatrixMultiplication(data, row_ptr, col_ptr, vec)
5 ResultMatrix.insert(i,0)
6 for i in range(0,vec_len):
----> 7 start, end = row_ptr[i], row_ptr[i + 1]
8 for k in range(start, end):
9 ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]
IndexError: list index out of range
FYI:
the last element of row_ptr will be size of the data list
The error message is pretty self-explanatory: You're trying to access
row_ptr[i + 1]
in a for loop that goes up tovec_len
, which is the length of your list. When you've reached the last iteration of your for loop andi = vec_len - 1
, theni + 1 = vec_len
, which is out of the range of your list (remember, Python lists are 0-initialised).To prevent this error, your range should only go up to
vec_len - 1
in your second for loop.