0

I have following problem, which I want to solve using numpy array elements. The problem is:

Matrix = np.zeros((4*4), dtype = bool) which gives this 2D matrix.

Matrix = [[False, False, False, False],
          [False, False, False, False],
          [False, False, False, False],
          [False, False, False, False]]

Les us suppose that we have an another array a = np.array([0,1], [2,1], [3,3])

a = [[0, 1], 
     [2, 1],
     [3, 3]]      

My question is: How to use the elements of the a array as indices to fill my matrix with True's. The output should seem like this

Matrix = [[False, True,  False, False], # [0, 1]
          [False, False, False, False],
          [False, True,  False, False], # [2, 1]
          [False, False, False, True]]  # [3, 3]

3
  • Matrix = np.zeros((4,4), dtype = bool) will give a 2D matrix, currently your code will give 1D array Commented Jan 13, 2022 at 17:54
  • a = np.array([[0,1], [2,1], [3,3]]) will give a 2D array Commented Jan 13, 2022 at 17:56
  • The answer provided by CJR makes what I want to do. Thanks Commented Jan 13, 2022 at 18:36

2 Answers 2

1
import numpy as np
Matrix = np.zeros((4*4), dtype = bool).reshape(4,4)

a = [[0, 1], 
     [2, 1],
     [3, 3]]

Unroll them into a proper pair of indexing arrays for a 2d array

a = ([x[0] for x in a], [x[1] for x in a])
Matrix[a] = True

>>> Matrix
array([[False,  True, False, False],
       [False, False, False, False],
       [False,  True, False, False],
       [False, False, False,  True]])
Sign up to request clarification or add additional context in comments.

1 Comment

It worked. Thanks for ur help (y)
0

Simple way to make the (4,4) bool array:

In [390]: arr = np.zeros((4,4), dtype = bool)
In [391]: arr
Out[391]: 
array([[False, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]])

Proper syntax for making a:

In [392]: a = np.array([[0,1], [2,1], [3,3]])
In [393]: a
Out[393]: 
array([[0, 1],
       [2, 1],
       [3, 3]])

Use the 2 columns of a as indices for the 2 dimensions of arr:

In [394]: arr[a[:,0],a[:,1]]=True
In [395]: arr
Out[395]: 
array([[False,  True, False, False],
       [False, False, False, False],
       [False,  True, False, False],
       [False, False, False,  True]])

1 Comment

This worked also fine. thanks for ur response :D

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.