如何从角度向量向量化创建 N 个旋转矩阵? [英] How to vectorize the creation of N rotation matrix from a vector of angles?

查看:78
本文介绍了如何从角度向量向量化创建 N 个旋转矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据:theta 是 N 个角的向量.

Data: theta is a vector of N angles.

问题:如何在矢量化时从 theta 创建 N 个二维旋转矩阵的矢量?

Question: How to create a vector of N 2D rotation matrix from theta while vectorizing?

如果没有向量化,我可以想到一个 for 循环:

Without vectorizing I can think of a for loop:

import numpy as np

N = 100
theta = np.random.rand(N)*2*np.pi

def R(theta_v):
    Rotation = np.empty((len(theta_v), 2, 2))
    for k, theta in enumerate(theta_v):
        Rotation[k] = np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)] ])
    return Rotation

Rotation = R(theta)

有没有办法避免for循环以实现更高效的代码?

Is there a way to avoid the for loop in order to achieve a more efficient code?

推荐答案

您可以使用 cos 和 sin 的矢量化版本来矢量化您的函数,然后重新排列结果:

You can vectorize your function by using the vectorized versions of cos and sin, then rearranging the result:

def R_vec(theta):
    c, s = np.cos(theta), np.sin(theta)
    return np.array([c, -s, s, c]).T.reshape(len(theta),2,2)

对于 N=100,矢量化版本比我计算机上的原始版本快 110 倍左右.

For N=100, the vectorized versions is about 110 times faster than the original on my computer.

这篇关于如何从角度向量向量化创建 N 个旋转矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆