【发布时间】:2020-05-26 07:10:47
【问题描述】:
我正在使用 Python 并希望遍历 Nx9 数组的每一行并从该行中提取某些值以与它们形成另一个矩阵。 N 值可以根据我正在阅读的文件而改变,但我在示例中使用了 N=3。我只需要每行的第 0、第 1、第 3 和第 4 个值形成一个我需要存储的数组。例如:
result = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
[11, 12, 13, 14, 15, 16, 17, 18, 19],
[21, 22, 23, 24, 25, 26, 27, 28, 29]])
#Output matrix of first row should be: ([[1,2],[4,5]])
#Output matrix of second row should be: ([[11,12],[14,15]])
#Output matrix of third row should be: ([[21,22],[24,25]])
然后我应该以提取值形成的 N 个矩阵结束 - 每行的 2D 矩阵。但是,形成的矩阵显示为 3D,因此在转置和减去时,我收到错误 ValueError: operands could not be broadcast together with shapes (2,2,3) (3,2,2)。我知道不能从 (2,2,3) 中减去 (3,2,2) 矩阵,那么如何获得 N 次二维矩阵?循环会更适合吗?有什么建议吗?
import numpy as np
result = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
[11, 12, 13, 14, 15, 16, 17, 18, 19],
[21, 22, 23, 24, 25, 26, 27, 28, 29]])
a = result[:, 0]
b = result[:, 1]
c = result[:, 2]
d = result[:, 3]
e = result[:, 4]
f = result[:, 5]
g = result[:, 6]
h = result[:, 7]
i = result[:, 8]
output = [[a, b], [d, e]]
output = np.array(output)
output_transpose = output.transpose()
result = 0.5 * (output - output_transpose)
【问题讨论】:
-
你能告诉我们这在数学上应该是什么样子吗?因为很明显,您不能从 (3,2,2) 中减去 (2,2,3) 矩阵。我认为你的矩阵需要,我猜,是回文的形状才能起作用。和(2,2,3)倒过来读是不一样的。它是 (3,2,2),所以你的一般公式 aMM^-1 只能在形状为回文的矩阵上工作。
-
请分享整个错误信息。