2

I have a 2d Matrix

matrix = np.array([[1,2],[3,4],[5,6]])
index = np.array([0, 1, 1])
add_value = np.array([1, 2, 3])

I want to add add_value to matrix but only to the elements corresponding to index in the index list. For example, 1 in add_value should be added to the first element in [1,2], which is 1, resulting in 2. So the output should be

np.array([[2,2],[3,6],[5,9]])
2
  • 2
    matrix[np.r_[:matrix.shape[0]], index] += add_value? Commented Jan 14, 2022 at 3:34
  • 1
    you are a genius. have a lovely day Commented Jan 14, 2022 at 3:36

2 Answers 2

2

Use a simple multi-dimensional indexing:

matrix[np.arange(matrix.shape[0]), index] += add_value

Or using python builtins:

matrix[tuple(zip(*enumerate(index)))] += add_value

Output:

array([[2, 2],
       [3, 6],
       [5, 9]])
Sign up to request clarification or add additional context in comments.

Comments

0
for i, x in enumerate(add_value):
    matrix[i][index[i]] += x

2 Comments

This will be slow on large arrays
Good to know thanks. For me it's the easiest way to understand what's happening.

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.