我有一个(6 x 6)
矩阵的集合,在我的代码中,我可能会得到5到6个矩阵(阶数为(6 x 6)。)
我想删除我拥有的这 5 到 6 个矩阵中的某些行
和列
。
所以我运行了一个for循环
假设现在,在该集合中我只有“一个”矩阵(a_matrix
阶6 x 6
)。
进入此 for 循环
的每个矩阵都应缩减为 2 x 2 矩阵
,如下所示。 (期望的输出)
这是我失败的尝试,这里 a_matrix
将不起作用,因为我的集合中只有一个 6 x 6
矩阵。
它显示错误为
ValueError:无法将输入数组从形状 (5) 广播到形状 (6)
import numpy as np
a_matrix = np.array ( [ [ 1, 2, 3, 4, 5, 6 ],
[ 7, 8, 9, 10, 11, 12 ],
[ 13, 14, 15, 16, 17, 18 ],
[ 19, 20, 21, 22, 23, 24 ],
[ 25, 26, 27, 28, 29, 30 ],
[ 31, 32, 33, 34, 35, 36 ]] )
total_no_of_matrices = 1
for i in range(total_no_of_matrices):
a_matrix[i] = np.delete(a_matrix[i], 0, 0)
a_matrix[i] = np.delete(a_matrix[i], 0, 0)
a_matrix[i] = np.delete(a_matrix[i], 1, 0)
a_matrix[i] = np.delete(a_matrix[i], 1, 0)
print(a_matrix)
所需的输出-(删除某些行和列后)
a_matrix = [[15, 18],
[33, 36]]
最佳答案
问题是 numpy 使数组尽可能静态。因此,如果您将数组声明为 nx6x6,您不能突然告诉它您希望矩阵 3 为 2x2。更好的方法是声明一个新数组来保存较小的矩阵。在某些情况下,您可以使 numpy 数组动态化,但通常效率非常低,并且通常您无论如何都会预先分配数组 - 如果不能,那么 numpy 数组可能不是正确使用的对象。我可能会采取以下方法:
import numpy as np
a_matrix = np.arange(1, 6 * 6 + 1).reshape((6, 6))
if a_matrix.ndim == 2:
a_matrix = a_matrix.reshape((1, a_matrix.shape[0], a_matrix.shape[1]))
total_no_of_matrices = a_matrix.shape[0]
reduced_matrices = np.zeros((total_no_of_matrices, 2, 2))
rows_to_delete = [0, 1, 3, 4]
cols_to_delete = [0, 1, 3, 4]
for i in range(total_no_of_matrices):
temp_matrix = np.delete(a_matrix[i, :, :], rows_to_delete, axis=0)
temp_matrix = np.delete(temp_matrix, cols_to_delete, axis=1)
reduced_matrices[i, :, :] = temp_matrix
print(a_matrix)
print(reduced_matrices)
此外,如果您想变得更奇特,您可以使用高级索引。但有时我发现很难理解,而且我一直使用 numpy。因此,如果有人阅读代码,可能会远离它,但这是另一种选择
another_way = a_matrix[:, np.array([[2, 2], [5, 5]]), np.array([[2, 5], [2, 5]])]
print(another_way)
关于python - 使用 for 循环从矩阵集合中删除(每个矩阵的)行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72521708/