How do you unroll a Numpy array of (mxn) dimentions into a single vector
Solution 1
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])
Solution 2
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).
FelipeG
Updated on June 18, 2022Comments
-
FelipeG about 2 years
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 pythonThank in advance.
-
FelipeG about 11 yearsJust a last question there is a built-in function in python if instead of a numpy array I have a normal list [[1,2,3],[4,5]] and I want [1,2,3,4,5]. Thanks
-
FelipeG about 11 yearsNever mind I found the answer in stackoverflow.com/questions/952914/… . Thank you anyway
-
Akavall about 11 yearsDownvoter, can you leave a comment? My answer did what OP was looking for, what's the problem?
-
Akavall about 11 yearsI don't know if you downvoted my answer, but I am sure downvoter's logic was as you describe in your post. My code was not an accurate translation of Matlab code to Python, I was going to delete my answer, but I can't since it is accepted.
-
Patrick Mineault about 11 yearsIt's good now, I've removed my downvote, which was due to the issues with dimension unravelling (row-first as in Matlab vs. column first as Python).