Reputation: 79
I have the following issue. I have around 500 files in .txt-format, which I need to process. They consist of a sign, a value (no matter which one) and a space behind and basically they are all on their own a matrix. I can read those files properly, but just at the stage where I need to find the first non-no-date value I have a problem. This is my code:
def FindStartingPoint(Matrix, NoDataValue, Rows, Cols):
RowCounter=0
ColCounter=0
for RowCounter in range (0, Rows):
for ColCounter in range((len(Matrix[0])-1), 0, -1):
CurrentValue=Matrix[RowCounter][ColCounter]
if CurrentValue>NoDataValue:
return RowCounter, ColCounter;
I know that the code is not wisely written, but due to documentation practices, I absolutely have to do it like this. The NoDataValue is zero (0). For matrix'es which have the format of x times y (x, y € R) I have no problems. Just take this matrix:
Rows: 8
Cols: 1
250.00
323.00
492.00
528.00
214.00
523.00
923.00
5823.00
Apparently I screwed up my indices (RowCounter & ColCounter) as I get this message:
IndexError: index 1 is out of bounds for axis 0 with size 1
I see my mistake: the ColCounter part does not run at all. I don't just understand why. I absolutely need to run through the matrix starting at the upper right value, so the very last value of the first row. Anybody see my mistake and could help me here pls?
Upvotes: 1
Views: 56
Reputation: 22776
You're already getting the sizes Rows
and Cols
, so no need to use len
here, also, you don't have to specify that you're starting from 0
, just using range(n)
means that you're starting from 0
by default. BTW, starting from the right means that you stop at zero, so, the range should be range(Cols - 1, -1, -1)
:
def FindStartingPoint(Matrix, NoDataValue, Rows, Cols):
RowCounter = 0
ColCounter = 0
for RowCounter in range (Rows):
for ColCounter in range(Cols - 1, -1, -1):
CurrentValue = Matrix[RowCounter][ColCounter]
if CurrentValue > NoDataValue:
return RowCounter, ColCounter;
However, if not all rows have the same number of columns (which doesn't really make it a matrix), the second loop should look like this:
for ColCounter in range(len(Matrix[RowCounter]) - 1, -1, -1):
Upvotes: 2