Search code examples
pythonnumpymatrix-multiplicationnumpy-ndarrayarray-broadcasting

Reordering numpy 4D-array


I'm having troubles understanding how to manage and modify numpy matrices. I find it very difficult to "picture" the matrices in my head.

I have a (4x2x1x1) matrix which I want to make into a (1x2x1x4) matrix, such that I can apply matrix multiplication with another matrix which have the shape (3x2x1x1).

Thanks in advance!


Solution

  • If your matrix is called matrix, matrix.shape = (1,2,1,4) (as in my example above) does the trick. NumPy will automatically notices if your new shape is "out of bounds", and automatically reorder the data correctly if it's not.

    EDIT: You can also use newMatrix = numpy.reshape(matrix, (1,2,1,4)) to create a new matrix as a reshape of your first matrix.