How do you unroll a Numpy array of (mxn) dimentions into a single vector


Question

I just want to know if there is a short cut to unrolling numpy arrays into a single vector. For instance (convert the following Matlab code to python):

Matlab way: A = zeros(10,10) %
A_unroll = A(:) % <- How can I do this in python

Thank in advance.

1
5
4/13/2013 2:43:04 PM

Accepted Answer

Is this what you have in mind?

Edit: As Patrick points out, one has to be careful with translating A(:) to Python.

Of course if you just want to flatten out a matrix or 2-D array of zeros it does not matter.

So here is a way to get behavior like matlab's.

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> # one way to get Matlab behaivor
... (a.T).ravel()
array([1, 4, 2, 5, 3, 6])

numpy.ravel does flatten 2D array, but does not do it the same way matlab's (:) does.

>>> import numpy as np
>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> a.ravel()
array([1, 2, 3, 4, 5, 6])
8
4/14/2013 12:38:21 AM

You have to be careful here, since ravel doesn't unravel the elements in the same that Matlab does with A(:). If you use:

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a.shape
(2,3)
>>> a.ravel()
array([1, 2, 3, 4, 5, 6])

While in Matlab:

>> A = [1:3;4:6];
>> size(A)
ans =

     2     3
>> A(:)

ans =

     1
     4
     2
     5
     3
     6

In Matlab, the elements are unraveled first down the columns, then by the rows. In Python it's the opposite. This has to do with the order that elements are stored in (C order by default in NumPy vs. Fortran order in Matlab).

Knowing that A(:) is equivalent to reshape(A,[numel(A),1]), you can get the same behaviour in Python with:

>>> a.reshape(a.size,order='F')
array([1, 4, 2, 5, 3, 6])

Note order='F' which refers to Fortran order (columns first unravelling).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon