Sam
Sam

Reputation: 324

Repeat element from a 2D matrix to a 3D matrix with numpy

I have a 2-D numpy matrix, an example

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

I would like, starting from M, to have a matrix like:

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

thus, the new matrix has 3 dimensions. How can I do?

Upvotes: 0

Views: 580

Answers (3)

frhyme
frhyme

Reputation: 1036

as another answerer already said, the matrix can't be three-dimensional. instead of it, you can make 3-dimensional np.array like below.

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

Upvotes: 0

Divakar
Divakar

Reputation: 221524

NumPy matrix class can't hold 3D data. So, assuming you are okay with NumPy array as output, we can extend the array version of it to 3D with None/np.newaxis and then use np.repeat -

np.repeat(np.asarray(M)[:,None],3,axis=1)

Sample run -

In [233]: M = np.matrix([[1,2],[3,4],[5,6]])

In [234]: np.repeat(np.asarray(M)[:,None],3,axis=1)
Out[234]: 
array([[[1, 2],
        [1, 2],
        [1, 2]],

       [[3, 4],
        [3, 4],
        [3, 4]],

       [[5, 6],
        [5, 6],
        [5, 6]]])

Alternatively, with np.tile -

np.tile(np.asarray(M),3).reshape(-1,3,M.shape[-1])

Upvotes: 2

zipa
zipa

Reputation: 27869

This should work for you:

np.array([list(np.array(i)) * 3 for i in M])

Upvotes: 1

Related Questions