NumPy: best way to multiply matrix by array?

I work with NumPy arrays, but sometimes I need to multiply them by arrays.

Now I am doing something like:

rotation_matrix = np.matrix([ ... ])
for vector in vectors:
    rotated_vec_mat = vector.T * rotation_matrix
    vector[:] = np.array(rotated_vec_mat)[0]

But this is ugly (and slow?).

Is there a cleaner way to do this?

+3
source share
1 answer

It might make sense to do this:

vector_arr = np.concatenate([vector[np.newaxis, :] for vector in vectors], axis=0)
rotated_vector_arr = np.dot(vector_arr, rotation_matrix)

Then the lines rotated_vector_arrare what you want. You can view all this as one matrix product and loop through the C / Fortran BLAS library.

There is no need to use the matrix () class for matrix multiplication, arrays work fine. matrix () overloads the * operator, but I find that it just confuses things.

+3
source

Source: https://habr.com/ru/post/1777537/


All Articles