Home > database >  Numpy: Generate matrix recursively
Numpy: Generate matrix recursively

Time:12-07

Is there a smart way to recursively generate matrices with increasing sizes in numpy? I do have a generator matrix which is

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

And in every further iteration, the size of both axes doubles, making a new matrix of the format:

[g_{n-1}, 0], [g_{n-1}, g_{n-1}]

which means that the new version would be:

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

Is there an easy way to obtain something like that? I could also generate a matrix of size (len(g)*2, len(g)*2) and try to fill it manually in two for-loops, but that seems extremely annoying.

Is there a better way?

PS: For those of you curious about it, the matrix is the generator matrix for polar codes.

CodePudding user response:

I don't see a straight-forward way to generate g_n, but you can reduce the two for-loops to one (along n) with:

# another sample
g = np.array([[1, 0], [2, 3]])

g = (np.array([[g,np.zeros_like(g)],[g, g]])
       .swapaxes(1,2).reshape(2*g.shape[0], 2*g.shape[1])
    )

Output:

array([[1, 0, 0, 0],
       [2, 3, 0, 0],
       [1, 0, 1, 0],
       [2, 3, 2, 3]])

CodePudding user response:

IIUC, one way using numpy.block:

g = np.array([[1, 0], [1, 1]])
g = np.block([[g, np.zeros(g.shape)], [g, g]])

Output (iteration 1):

array([[1., 0., 0., 0.],
       [1., 1., 0., 0.],
       [1., 0., 1., 0.],
       [1., 1., 1., 1.]])

Output (iteration 2):

array([[1., 0., 0., 0., 0., 0., 0., 0.],
       [1., 1., 0., 0., 0., 0., 0., 0.],
       [1., 0., 1., 0., 0., 0., 0., 0.],
       [1., 1., 1., 1., 0., 0., 0., 0.],
       [1., 0., 0., 0., 1., 0., 0., 0.],
       [1., 1., 0., 0., 1., 1., 0., 0.],
       [1., 0., 1., 0., 1., 0., 1., 0.],
       [1., 1., 1., 1., 1., 1., 1., 1.]])
  • Related