stacking 2D matrix using Python
Question: I have a script that reshapes a 1024x1024 matrix into 32x32 matrices. Here it
is the code:

    
    
    import numpy as np
    
    
    filename = r'bb1e03'                    
    background = r'bb1e03_background'               
    
    size = 1024
    resize = 32
    
    n = np.arange(size)
    T0 = np.loadtxt(filename, unpack=False)
    bg = np.loadtxt(background, unpack=False)
    
    T = T0-bg                                               
    
    for s in n: # s here is the row number
        B = np.reshape(T[s], (resize, resize))
        B_rev = B[...,::-1]                                                                 
        name = str(filename) + '_column_'+ str.zfill(str(s), 4)   
        np.savetxt(name+'.txt', B_rev)
    

Now I need all 32x32 matrices stacked so that in the end I have a 32x32x1024
matrix. Could you please tell me how I can do that? I have found that
np.dstack would do the job but I have no idea how to include it in the script.

Thank you.


Answer: Since `np.dstack` needs a tuple of all of the matrices to stack you are going
to have to store them separately as you go along anyway.

A simple solution to your problem would be to put the reshaped matrices in
place in the stacked structure as you generate them.

    
    
    stacked = np.empty((32, 32, 1024))
    for s in xrange(1024):
        B = T[s].reshape((32, 32))
        B_rev = B[..., ::-1]
        stacked[...,s] = B_rev
    

You could also do this in one step with the one liner

    
    
    stacked = T.reshape((1024,32,32)).transpose((1,2,0))[:,::-1]
    

This method should be preferred as with some brief benchmarking I've found it
to be **much** (1000x) faster than the plain python loop.

