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):
A = zeros(10,10) %
A_unroll = A(:) % <- How can I do this in python
Thank in advance.
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
>>> 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])
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).