Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Elegant Implementation of MATLAB's "vec" Function in NumPy

In MATLAB there is a function referred to as vec that takes a matrix and stacks the columns into a single vector. For example if we call the following matrix "X":

[1 2]
[3 4]

then vec(X) would return the vector:

[1]
[3]
[2]
[4]

There doesn't seem to be any direct implementation of this, and the "NumPy for MATLAB users" doesn't have a direct equivalent.

So, if one is given a numpy array (representing the matrix), what would a very elegant line of NumPy be to reproduce this result? Just curious to see how concise / elegant this can be made. Thanks!

like image 841
Vincent Russo Avatar asked Aug 11 '14 16:08

Vincent Russo


2 Answers

You can use the "Fortran" order option to e.g. reshape:

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a.reshape((-1, 1), order="F")
array([[1],
       [3],
       [2],
       [4]])
like image 157
jonrsharpe Avatar answered Oct 18 '22 03:10

jonrsharpe


I think what you want is flatten()

EG:

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])

>>> a.flatten('F')
>>> array([1, 3, 2, 4])

Thanks @jonrsharpe, I actually just looked it up too! BTW: transpose the array using a.T.flatten() is an alternate to changing the order using order='F'

like image 30
Mark Mikofski Avatar answered Oct 18 '22 01:10

Mark Mikofski