Search code examples
pythonarraysnumpymatrixvalueerror

Numpy ValueError: shapes (4,4) and (3,) not aligned: 4 (dim 1) != 3 (dim 0)


I want to Rotate the Vector vc by the rotation matrix in the numpytestarray but i get an ValueError.

This is my Code ( reduced to the essentials)

import numpy as np

vc = np.array([0,0,1])

numpytestarray = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])

new_vc = numpytestarray.dot(vc)
print(new_vc)

How can i Fix this Problem?


Solution

  • Your rotation matrix and vector should be the same size, e.g.:

    • rotation matrix of size 2x2 corresponds to rotation in 2D, of a 2D vector [x, y]
    • rotation matrix of size 3x3 corresponds to rotation in 3D, of a 3D vector [x, y, z]

    Your vector vc is in 3D [0, 0, 1], however you try to rotate it in 4 dimentions using rotation matrix of size 4x4.

    You need to either change vector size:

    import numpy as np
    vector = np.array([0,0,0,1])
    rotation_matrix = np.array([
        [-1, 0, 0, 0],
        [0, -1, 0, 0],
        [0, 0, -1, 0],
        [0, 0, 0, -1]])
    rotated = rotation_matrix.dot(vector)
    print(rotated) # [0, 0, 0, -1]
    

    or rotation matrix size:

    import numpy as np
    vector = np.array([0,0,1])
    rotation_matrix = np.array([
        [-1, 0, 0],
        [0, -1, 0],
        [0, 0, -1]])
    rotated = rotation_matrix.dot(vector)
    print(rotated) # [0, 0, -1]