所以我想改变 matrix_a
中的值根据 matrix_b
中的值.所以如果值在 matrix_b
在位置 0,0
是 1
,然后是 result_matrix
中的元素在 0,0
应该是位于 1,1
的元素在 matrix_a
.我已经使用以下代码进行了这项工作:
import numpy as np
matrix_a = np.matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix_b = np.matrix([[1, 1, 0],
[0,-1, 0],
[0, 0, -1]])
result_matrix = np.zeros((3,3))
for x in range(matrix_b.shape[0]):
for y in range(matrix_b.shape[1]):
value = matrix_b.item(x,y)
result_matrix[x][y]=matrix_a.item(x+value,y+value)
print(result_matrix)
这导致:
[[5. 6. 3.]
[4. 1. 6.]
[7. 8. 5.]]
现在这在大型矩阵上很慢,我觉得这可以使用 numpy 或 scipy 的函数之一进行优化。有人能告诉我如何更有效地做到这一点吗?
最佳答案
使用 np.indices
ix = np.indices(matrix_a.shape)
matrix_a[tuple(ix + np.array(matrix_b))]
Out[]:
matrix([[5, 6, 3],
[4, 1, 6],
[7, 8, 5]])
作为忠告,尽量避免使用
np.matrix
- 这只是为了兼容旧的 MATLAB
代码,并打破了很多 numpy
职能。 np.array
99% 的时间都可以正常工作,其余时间 np.matrix
会混淆核心 numpy
用户。
关于python - 根据另一个矩阵中的值移动一个矩阵中的值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715074/