如何将(mxn)尺寸的Numpy数组展开为单个向量
我只想知道将numpy数组展开为单个向量是否存在捷径.例如(将以下Matlab代码转换为python):
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方式:
A =零(10,10)%
A_unroll = A(:)%<-如何在python中做到这一点
Matlab way:
A = zeros(10,10) %
A_unroll = A(:) % <- How can I do this in python
谢谢.
这是您要记住的吗?
正如Patrick指出的那样,在将A(:)转换为Python时必须要小心.
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.
因此,这是一种获得类似matlab行为的方法.
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
可以展平2D数组,但是不能像matlab的(:)
一样进行.
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])