0

I want to index a lot of python matrices to carry out calculations (mainly dot products) on corresponding elements. I'm having a problem using the non-zero values of one matrix to index a matrix that has fewer columns - it throws errors saying the index is out of bounds. Is there a way for me to tell python not to care about when the index is out of bounds - to ignore those ones and just deal with the ones that are in bounds? The code is something like this:

for u in range (n): # u = row:
    U[R[u,:]!=0, u] ...

the dimension of U is (dxn) and dimension of R is (nxm) where m > n > d (usually).

I was hoping there is something built in in python to ignore when the index is out of bounds?

  • No you'd have to do `len(...)` first to check the length or use a `try / except` case. – Torxed Nov 11 '15 at 15:22
  • 1
    Possible duplicate of [I want to exception handle 'list index out of range.'](http://stackoverflow.com/questions/11902458/i-want-to-exception-handle-list-index-out-of-range) – Torxed Nov 11 '15 at 15:22

1 Answers1

1

I just realised that I could find the shape of the matrix U and use it to put a bound on the indexing of R like follows:

n,m = U.shape
U[R[u,0:n]!=0, u]

this means it never goes out of bounds as we're only looking at the part of R that is in the bounds of U