22

I'm translating a program from matlab to Python.

The matlab code uses the method permute:

B = PERMUTE(A,ORDER) rearranges the dimensions of A so that they
%   are in the order specified by the vector ORDER.  The array produced
%   has the same values as A but the order of the subscripts needed to 
%   access any particular element are rearranged as specified by ORDER.
%   For an N-D array A, numel(ORDER)>=ndims(A). All the elements of 
%   ORDER must be unique.

Is there an equivalent method in Python/NumPy ?

LynnH
  • 7,216
  • 3
  • 15
  • 13
  • [numpy.rollaxis](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html#numpy.rollaxis) is close ... – mgilson Oct 08 '12 at 18:38
  • 2
    @Maurits That's random permutation. Since there's nothing about random in the description of the function "permute" in matlab i assume it isn't random... – LynnH Oct 08 '12 at 18:39

1 Answers1

28

This is rolled into the transpose function in numpy.ndarray. The default behavior reverses the order, but you can supply a list of your own order.

aganders3
  • 5,838
  • 26
  • 30
  • But what if I have array of size [4, 6] and I want to make it [1, 4, 6]. In MATLAB it would be `mX = permute(mA, [3, 1, 2]);`. Yet `transpose` in Python won't do it (As the shape of the array doesn't have the third dimension). Is there a solution for that (I don't have Numpty with `rollaxes`, So think Numpy 0.9.xxxx) – Royi Apr 21 '18 at 16:35
  • If you want to add an axis I'd use something like `A = A[np.newaxis, ...]` or `A = A[:, np.newaxis, :]` depending on where you want the new axis. You can transpose the axes after that if needed. – aganders3 Apr 23 '18 at 18:28