Matlab vs Python-矢量化和重塑阵列



考虑三个不同的MATLAB数组:abc。它们都是同等大小的数组。假设64 x 64。现在,为了重新组织其中一个数组的元素,以另一个数组的形式在另一个数组X中重新组织,我可以做以下操作:

X = [X a(:)];

现在,我有一个4096 x 1数组。如果我想在每列中包含一个数组,则不同数组的元素,我可以重复上面的B和c。

的过程。

在python中是否有相当于?

您可以使用np.concatanate函数。示例:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
res = np.concatenate([a,b,c])

也可以按以下方式顺序进行:

res = a
res = np.concatenate([res,b])
res = np.concatenate([res,c])

结果:

res = array([1, 2, 3, 4, 5, 6, 7, 8, 9])

为了实现4x1,您可以使用reshape()功能是这样:

np.reshape((-1, 1))
a = np.zeros((2,2)) #creates 2,2 matrix
print(a.shape) #2,2
print(a.reshape((-1, 1)) #4,1

这将确保您在产生的数组中实现1列,而与设置为 -1 的行元素无关。

如注释中所述,您可以使用numpy的flatten()函数,使您的矩阵将其平放入向量。例如;如果您有2x2矩阵,flatten()将达到1x4矢量。

a = np.zeros((2,2)) # creates 2,2 matrix
print(a.shape) # 2,2
print(a.flatten()) # 1,4

最新更新