bobsacameno
bobsacameno

Reputation: 765

python - numpy - many matrices multiplying many vectors

I have a set of many matrices each corresponding to a vector. I want to multiply each matrix by its vector smartly. I know I can putt all the matrices in a big block diagonal form, and multiply it by a big combined vector.

I want to know if there is a way to use numpy.dot to multiply all of them in an efficient way.

I have tried to use numpy.stack and the numpy.dot, but I can't get only the wanted vectors.

To be more specific. My matrices look like:

R_stack = np.stack((R, R2, R3))

which is

array([[[-0.60653066,  1.64872127],
    [ 0.60653066, -1.64872127]],

   [[-0.36787944,  2.71828183],
    [ 0.36787944, -2.71828183]],

   [[-0.22313016,  4.48168907],
    [ 0.22313016, -4.48168907]]])

and my vectors look like:

p_stack = np.stack((p0, p0_2, p0_3))

which is

array([[[0.73105858],
    [0.26894142]],

   [[0.88079708],
    [0.11920292]],

   [[0.95257413],
    [0.04742587]]])

I want to multiply the following: R*p0, R2*p0_2, R3*p0_3.

When I do the dot :

np.dot(R_stack, p_stack)[:,:,:,0]

I get

array([[[ 0.        , -0.33769804, -0.49957337],
    [ 0.        ,  0.33769804,  0.49957337]],

   [[ 0.46211716,  0.        , -0.22151555],
    [-0.46211716,  0.        ,  0.22151555]],

   [[ 1.04219061,  0.33769804,  0.        ],
    [-1.04219061, -0.33769804,  0.        ]]])

The 3 vectors I'm interested in are the 3 [0,0] vectors on the diagonal. How can I get them?

Upvotes: 0

Views: 327

Answers (2)

bobsacameno
bobsacameno

Reputation: 765

Another way I found is to use numpy.diagonal

np.diagonal(np.dot(R_stack, p_stack)[:,:,:,0], axis1=0, axis2=2)

which gives a vector in each column:

array([[0., 0., 0.],
   [0., 0., 0.]])

Upvotes: 1

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

You are almost there. You need to add a diagonal index on 1st and 3rd dimensions like so:

np.dot(R_stack, p_stack)[np.arange(3),:,np.arange(3),0]

Every row in the result will correspond to one of your desired vectors:

array([[-3.48805945e-09,  3.48805945e-09],
       [-5.02509157e-09,  5.02509157e-09],
       [-1.48245199e-08,  1.48245199e-08]])

Upvotes: 1

Related Questions