Python-Numpy : 3D matrix * 2D vector fast calculation

标签 python arrays performance numpy matrix

大家好,

这是我想做的。我有两个数组:

  • rotation_matrices 包含 50 个二维旋转矩阵。每个旋转矩阵的形状为 (2,2)。因此,rotation_matrices 的形状为 (2,2,50)。
  • vectors 包含 50 个二维向量。因此,它的形状为 (2,50)。

我想要(如果它存在)一个单行 numpy 操作,它给我包含旋转向量的 (2,50) 数组,我们称它为 rotated_vectors。我的意思是,rotated_vectors 的第 k 个元素包含第 k 个旋转矩阵与第 k 个向量的乘积。

目前,我想出了以下循环:

for ind,elt in enumerate(np.arange(nb_of_vectors)):
            rotated_vector[ind] = np.dot( rotation_matrices[:,:,ind], vectors[:,ind] )

我认为还有改进的余地。如果您有任何建议,欢迎您。

感谢您的宝贵时间。

猎豹

最佳答案

您的坐标轴顺序不正常。首先,您需要将矩阵轴放在最后:

rotation_matrices = np.rollaxis(rotation_matrices, -1)  # shape (50, 2, 2)
vectors = np.rollaxis(vectors, -1)                      # shape (50, 2)

这将使您现有的循环更具可读性:

for ind in np.arange(nb_of_vectors):
    rotated_vector[ind] = np.dot(rotation_matrices[ind], vectors[ind])

但是,您可以使用矩阵乘法运算符(或 python < 3.5 中的 np.matmul)

rotated_vectors = (a @ vectors[...,None])[...,0]
# rotated_vectors = np.matmul(a, vectors[...,None])[...,0]

[...,None] 将向量数组 (shape (n,) 转换为列矩阵数组 (shape (n, 1)), 尾部的 [...,0] 将列矩阵转换回向量

关于Python-Numpy : 3D matrix * 2D vector fast calculation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094100/

相关文章:

python - RuntimeError : No recommended backend was available.(带 Python 的 key 环)

JavaScript - 迭代数组以检查条件

java - 正确处理异常

r - 何时在 R 中使用配对列表?

python - 在代码中放置模运算

python - 使用 python selenium 单击不可见的元素

python - pbkdf2 和哈希比较

python - python中的图像旋转令人困惑

c# - 获取数组中特定项目的索引

mysql - 后端工作或 sql 查询哪个进程会更快?