Most elegant implementation of MATLAB "vec" function in NumPy
MATLAB has a function called vec
that takes a matrix and stacks the columns into one vector. For example, if we name the following matrix "X":
[1 2]
[3 4]
then vec(X)
will return a vector:
[1]
[3]
[2]
[4]
There seems to be no direct implementation of this, and " NumPy for MATLAB Users " has no direct equivalent.
So, given a numpy array (representing a matrix), what would a very elegant NumPy line be able to reproduce this result? Just curious to see how concise / elegant it can be. Thank!
source to share
I think what you want 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! BTW: Transposing an array using a.T.flatten()
is an alternative to changing the order usingorder='F'
source to share
For a one-dimensional result, use X.T.ravel()
or X.T.flatten()
. For a two dimensional column, use X.T.reshape(-1,1)
.
source to share