1

I have following numpy matrix:

import numpy as np
matrix = np.array([[1,2,3],[4,5,6]])

and a numpy vector:

vector = np.array([1,2])

where each element in the vector represents for each row of the matrix, the number of elements I want to retain. I would like to replace all other elements in the matrix with 0.

The final matrix should look like:

matrix_output = np.array([[1,0,0],[4,5,0]])

What is the quickest way ?

2 Answers 2

2

Could do something simple like this:

import numpy as np

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

for row, index in enumerate(vector):
    matrix[row, index:] = 0

print(matrix)
[[1 0 0]
 [4 5 0]]
Sign up to request clarification or add additional context in comments.

Comments

1

try

mask = vector[:,None]<=np.arange(3)
matrix[mask] = 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.