Home > Mobile >  Dynamically create matrix from a vectors in numpy
Dynamically create matrix from a vectors in numpy

Time:12-04

I'm trying to create a matrix of shape Nx3 where N is not known at first. 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.

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"

CodePudding user response:

The error you are seeing is caused by trying to stack empty arrays together using np.vstack(). When you create an empty array with np.array([[],[],[]]), the resulting array has shape (3, 0), which means that it has 3 rows but no columns. When you try to stack this empty array with another array using np.vstack(), the resulting array has shape (3, 0), which means that it still has 3 rows but no columns, and this is why you are seeing the error "along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 3".

To fix this issue, you can initialize the F array with the correct number of rows and columns before you start the loop. For example, you can create an empty array with shape (0, 3) like this:

F = np.empty((0, 3))
  • Related