是否有将转换矩阵应用于一组向量的矢量方法?

发布于 2025-02-09 12:02:57 字数 991 浏览 3 评论 0原文

想象一下,您有一组向量,例如轨迹的形式。是否有一种矢量化的方式将转换矩阵一次应用于所有数据点,或者您是否与前循环相处?这是一些示例代码:

import numpy as np


angle = np.deg2rad(90)
rotM = np.array(
    [
        [np.cos(angle), -np.sin(angle), 0],
        [np.sin(angle),  np.cos(angle), 0],
        [            0,              0, 1],
    ]
)

# trajectory with columns t, x, y, z
trajectory = np.array(
    [
        [1, 1, 0, 0],
        [2, 2, 1, 0],
        [3, 3, 2, 0],
        [4, 4, 3, 1],
        [5, 6, 4, 2],
        [6, 9, 5, 3],
    ]
)

# transform coordinates
for i in range(len(trajectory)):
    trajectory[i][1:] = np.dot(rotM, trajectory[i][1:])

到目前为止,我发现的只是 numpy.linalg.multi_dot ,以及这两个帖子(一个“ https://stackoverflow.com/q/28130787/5472354"> two ),似乎不适用于我的情况。

Imagine you have a group of vectors, e.g. in the form of a trajectory. Is there a vectorized way of applying the transformation matrix to all data points at once, or are you stuck with a for-loop? Here is some sample code:

import numpy as np


angle = np.deg2rad(90)
rotM = np.array(
    [
        [np.cos(angle), -np.sin(angle), 0],
        [np.sin(angle),  np.cos(angle), 0],
        [            0,              0, 1],
    ]
)

# trajectory with columns t, x, y, z
trajectory = np.array(
    [
        [1, 1, 0, 0],
        [2, 2, 1, 0],
        [3, 3, 2, 0],
        [4, 4, 3, 1],
        [5, 6, 4, 2],
        [6, 9, 5, 3],
    ]
)

# transform coordinates
for i in range(len(trajectory)):
    trajectory[i][1:] = np.dot(rotM, trajectory[i][1:])

All I found so far is numpy.linalg.multi_dot, and these two posts (one, two), none of which seem to apply to my case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

注定孤独终老 2025-02-16 12:02:58

对于这种情况,请与np.matmul/@一起使用广播。您可以将3x3 martrix乘以向量的NX3X1数组:

trajectory[:, 1:] = rotM @ trajectory[:, 1:, None]

更清洁,更灵活的解决方案可能是使用scipy.spatial.transform.transform.rotation.rotation.rotation对象,而不是手工制作矩阵:

rotM = Rotation.from_euler('z', angle)
trajectory[:, 1:] = rotM.apply(trajectory[:, 1:])

不需要 自己:在这种情况下,添加垫片尺寸。

For this case, use broadcasting along with np.matmul/@. You can multiply a 3x3 martrix by an Nx3x1 array of vectors:

trajectory[:, 1:] = rotM @ trajectory[:, 1:, None]

A cleaner and more flexible solution might be to use scipy.spatial.transform.Rotation objects instead of hand-crafting the matrix yourself:

rotM = Rotation.from_euler('z', angle)
trajectory[:, 1:] = rotM.apply(trajectory[:, 1:])

No need to add shim dimensions in this case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文