Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 992
FelipeG Avatar asked Apr 13 '13 14:04

FelipeG


1 Answers

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])
like image 170
Akavall Avatar answered Sep 21 '22 05:09

Akavall