简体   繁体   English

从 numpy 中的向量动态创建矩阵

[英]Dynamically create matrix from a vectors in numpy

I'm trying to create a matrix of shape Nx3 where N is not known at first.我正在尝试创建一个形状为 Nx3 的矩阵,其中 N 一开始是未知的。 This is what I'm basically trying to do:这就是我基本上想要做的:

    F = np.array([[],[],[]])
    for contact in contacts:
        xp,yp,theta = contact
        # Create vectors for points and normal
        P = [xp, yp, 0]
        N = [np.cos(theta), np.sin(theta), 0]
        # Calculate vector product
        cross_PN = np.cross(P,N)
        # f = [mz, fx, fi]
        mz = cross_PN[2]
        fx = N[0]
        fy = N[1]
        f = np.array([mz, fx, fy])
        F = np.vstack([F, f])

But this code doesn't work.但是这段代码不起作用。 I can do similar thing in Matlab very easily, but that is not the case in Python using numpy.我可以很容易地在 Matlab 中做类似的事情,但在使用 numpy 的 Python 中情况并非如此。

Any help is greatly appreciated.任何帮助是极大的赞赏。 Thank you谢谢

I would like to create a matrix by adding new rows, but in the beginning the matrix is empty.我想通过添加新行来创建一个矩阵,但一开始矩阵是空的。 That is why I receive the error: "along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 3"这就是为什么我收到错误消息:“沿着维度 1,索引 0 处的数组大小为 0,索引 1 处的数组大小为 3”

Based on your comments and suggestion, I guess the correct and more efficient way to do this is the following:根据您的意见和建议,我想正确且更有效的方法如下:

L = len(contacts)
F = np.zeros((L, 3))
for ii in range(L):
    xp,yp,theta = contacts[ii]
    # Create vectors for points and normal
    P = [xp, yp, 0]
    N = [np.cos(theta), np.sin(theta), 0]
    # Calculate vector product
    cross_PN = np.cross(P,N)
    # f = [mz, fx, fi]
    mz = cross_PN[2]
    fx = N[0]
    fy = N[1]
    fi = np.array([mz, fx, fy])
    F[ii] = fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM