Reshape 4d numpy array for 2d array while saving array locations

I have a 4 dimensional array with sizes (N, N, Q, Q) . Therefore, given the row and column index (i, j) , mat[i,j] is a QxQ matrix. I want to change this array to form (N*Q, N*Q) so that

 array([[[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]]], [[[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]]) 

goes into

 array([[ 0., 1., 4., 5.], [ 2., 3., 6., 7.], [ 8., 9., 12., 13.], [ 10., 11., 14., 15.]]) 

You can see that mat[0,0] goes into new_mat[0:2, 0:2] . Currently mat.reshape(N*Q, N*Q) takes mat[0,0] to new_mat[0:4, 0] (which I don't want). How can I use reshape or rollaxis or something similar to modify this array? Ultimately, I want to build it using imshow , I'm currently stuck. I find this easy to do, I just haven't figured it out yet.

+7
python numpy
source share
1 answer

Nevermind, I figured it out. np.swapaxes(1, 2) was the missing item that I needed.

The answer is to do mat.swapaxes(1, 2).reshape(N*Q, N*Q) .

Feel stupid to post without trying to figure yourself out for too long, but I will leave it so others can benefit from it.

+5
source share

All Articles