C1W2_Assignment Index Error

I am doing the back substitution function for Gaussian Elimination. My code says I have an index error. I put print statements throughout my code but those don’t work. My code makes sense to me, so I dont know why there is an error. Any tips for me to try?

a common error is forgetting python is zero-based indexed. I.e. the top most row is row 0, the last row is row n-1.

Okay, I understand that. I never made changes to the loops since that wasn’t in the directions.

the line I doubt the most is when I am supposed to replace the updated row in the matrix.

M[j] = row_to_reduce

maybe i do not understand this. but I think the other instances with index are fine in my code

We aren’t supposed to share source code, but you can share the exception trace. The way exception traces work, it should point exactly at the line that has the problem, right? You shouldn’t have to wonder which line has the problem. If that point doesn’t help, then please just “copy/paste” the full exception trace here.

I’m curious why they don’t work. Can you post a screen capture image?

i’m a little fuzzy on accessing multi dim arrays, but I would normally write out M[j,:] to be sure it replaces the row properly.

If that’s not it, the easiest way to debug for me was to call the function on known matrix and print out the major vars at each step to see what was going wrong (M, row_to_reduce, value, etc.). Would show errors like trying to access a row but only accessing the index, etc.

Jeremy

Hi, Jeremy.

It turns out either way to write the LHS of that assignment works.

I totally agree with your suggestion for how to debug a situation like this. Start with a concrete example. Work it out with pencil and paper so that you know what should be happening. Then instrument the code with print statements to show what’s actually happening.

I recommend using M[j,:].

If you use the current notebook version, it recommends iterating from the bottom to the top by using for row in reversed(range(num_rows)).

This makes all of the other indices very simple, because you don’t have to do any math on them.

Okay. Here is my exception trace:

An exception was thrown while running your function: index 7 is out of bounds for axis 0 with size 3.
Input matrix:
[[1 0 0 5]
[0 1 0 6]
[0 0 1 7]]

I added print statements like print(f"substitution_row: {substitution_row}") under variables for index, value, j, etc

Tip for those who find this thread later.

Be sure you follow the instructions about when to use “row” vs. “substitution_row”.

1 Like