0

I have a list of matrix indices and want to access a matrix by these indices.

Example:

indices = [(2, 0), (2, 1), (2, 2)]
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mat[indices] = 0

This should result in [[1, 2, 3], [4, 5, 6], [0, 0, 0]], but unfortunately I always get "list indices must be integers, not list".

EDIT

As user2357112 suggests in his comment I tried the following now:

mat = numpy.array(mat)
indices = numpy.array(indices)
mat[indices] = 0

But unfortunately the whole matrix is filled with 0 now.

1
  • 3
    If you want to use NumPy syntax, you need a NumPy array, not a list of lists. Call np.array on your matrices. Commented Jun 3, 2014 at 9:46

2 Answers 2

2

indices is a regular list of tuples and can't be used to get an element of your regular mat. What you can do is iterate over your list to get your indices:

for x, y in indices:
    mat[x][y] = 0

If you want to use numpy methods, you need to create a numpy array. Indeed, np.array structure allows to use tuple to access to an element:

mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
for item in indices:
    mat[item] = 0
Sign up to request clarification or add additional context in comments.

2 Comments

Wasn't me ... your solution works fine (especially since your last edit). Accepting it and voting it up.
seems reasonable to me, you could add that if he wanted to do mat[indices] = 0 the indicies would have to be converted into [[2,2,2],[0,1,2]] by for example zip(*indices)
0

You can use zip(*indices) to access a numpy array by an indices list:

import numpy as np

indices = [(2, 0), (2, 1), (2, 2)]
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

>> mat[zip(*indices)]
array([7, 8, 9])
>> mat[zip(*indices)] = 0
>> mat
array([[1, 2, 3],
       [4, 5, 6],
       [0, 0, 0]])

2 Comments

Is this a question?
This is an alternative answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.