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!
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]])
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With