NetUser5y62
NetUser5y62

Reputation: 145

Numpy Matrix Modulo Index Extraction

Suppose I have a 2-dimensional matrix A, say

A = np.mat([[1,2,3,4], 
            [5,6,7,8],
            [9,10,11,12]])

how can I change all elements in row 1 with column index modulo 2 to 0? I.e., I would like to obtain

np.mat([[1,2,3,4], 
        [0,6,0,8], 
        [9,10,11,12]])

I have tried

A[1][np.arange(len(A))%2==0] = 0

which results in IndexError.

Upvotes: 0

Views: 224

Answers (1)

kuzand
kuzand

Reputation: 9806

Column index % 2 = 0 means that the index is an even integer. You can change the elements of the first row at even column indexes to 0 as follows:

A[1, ::2] = 0  # 2 is the step

If you want to do it as your (incorrect) A[1][np.arange(len(A))%2==0] = 0, you should change it to

A[1, np.arange(A.shape[1]) % 2 == 0] = 0

where A.shape[1] is the number of columns (whereas len(A) gives you the number of rows).

Upvotes: 1

Related Questions