1

Consider the following code:

import numpy as np 
index_info = np.matrix([[1, 1], [1, 2]])
value =  np.matrix([[0.5, 0.5]])
initial = np.zeros((3, 3))

How can I produce a matrix, final, which has the structure of initial with the elements specified by value at the locations specified by index_info WITHOUT a for loop? In this toy example, see below.

final =  np.matrix([[0, 0, 0], [0, 0.5, 0.5], [0, 0, 0]])

With a for loop, you can easily loop through all of the index's in index_info and value and use that to populate initial and form final. But is there a way to do so with vectorization (no for loop)?

2 Answers 2

2

Convert index_info to a tuple and use it to assign:

>>> initial[(*index_info,)]=value
>>> initial
array([[0. , 0. , 0. ],
       [0. , 0.5, 0.5],
       [0. , 0. , 0. ]])

Please note that use of the matrix class is discouraged. Use ndarray instead.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this with NumPy's array indexing:

>>> initial = np.zeros((3, 3))

>>> row = np.array([1, 1])
>>> col = np.array([1, 2])

>>> final = np.zeros_like(initial)
>>> final[row, col] = [0.5, 0.5]
>>> final
array([[0. , 0. , 0. ],
       [0. , 0.5, 0.5],
       [0. , 0. , 0. ]])

This is similar to @PaulPanzer's answer, where he is unpacking row and col from index_info all in one step. In other words:

row, col = (*index_info,)

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.