Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to expand a 2d matrix to 3d by replacing the scalar with a vector in numpy

I have a 2d array like this:

a = np.array([[1, 0, 1],
              [0, 0 ,0]])

with shape (2,3). Indexing at some point would give a scalar, for example a[0,0] = 1 How can I turn this into a 3d array by replacing the scalar with a vector of length x filled with the initial scalar? For example say x = 5, I would want a[0,0] = [1,1,1,1,1] , a[0,1] = [0,0,0,0,0], … and the shape of a to be (2,3,x)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just use a.repeat() and then reshape:

x = 5
new_a = a.repeat(x).reshape(*a.shape, -1)

Output:

>>> new_a
array([[[1, 1, 1, 1, 1],
        [0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1]],

       [[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]]])

>>> new_a[0, 0]
array([1, 1, 1, 1, 1])

>>> new_a[0, 1]
array([0, 0, 0, 0, 0])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading