0

I can change a set of values of a numpy matrix, passing the indices that I want to change in a list form, e.g. matrix[[some first indices], [some second indices]] = 1

I'm trying to do this but with only one list of indices and then for each element of that list as the first index and the whole list as the other index. Here the example:

import numpy as np

#Matrix
matrix = np.zeros((5,5))

# Indices
elements = [1,2,3]

# Way that works
for i in elements:
    matrix[i, elements] = 1

I would like to do this as a list comprehension, but I cannot figure out how, and, also, I'm not sure if it is a good practice. Something like matrix[[(i,elements) for i in elements]] = 1

Also thinking about to do it with itertools, for example matrix[(itertools.permutation(elements, 2))] = 1. But any of those approaches work, and I'm not sure why.

4
  • Are you just trying to set the whole matrix to 1? If so, then just matrix += 1 Commented Oct 17, 2018 at 15:12
  • No, for every element on the list as a first index, and the entire list as a second. Commented Oct 17, 2018 at 15:15
  • I'm not sure what you mean by that. Can you post your expected output? Commented Oct 17, 2018 at 15:16
  • A list comprehension should be used to create a new list. While possible, it really shouldn't be used for side effects (e.g. modifying some other object). It isn't a total replacement for a loop. Commented Oct 17, 2018 at 15:50

2 Answers 2

3

You need to access the 2d-matrix with row and colum arrays as index:

import numpy as np
matrix = np.zeros((5,5))
elements = [1,2,3]
matrix[np.c_[elements], elements] = 1
# array([[0., 0., 0., 0., 0.],
#   [0., 1., 1., 1., 0.],
#   [0., 1., 1., 1., 0.],
#   [0., 1., 1., 1., 0.],
#   [0., 0., 0., 0., 0.]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, actually is a much better way than with list comprehension or itertools.
2

You can create a slice from the first to the last element (+1) of elements (provided elements is ordered):

s = slice(elements[0], elements[-1]+1)

matrix[s, elements]= 1 
# [[0. 0. 0. 0. 0.]
# [0. 1. 1. 1. 0.]
# [0. 1. 1. 1. 0.]
# [0. 1. 1. 1. 0.]
# [0. 0. 0. 0. 0.]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.