AStudent
AStudent

Reputation: 49

Multiply two Eigen vectors by corresponding elements

I have two Eigen vectors (vectorOne and vectorTwo) of my defined type( see below for my type).

typedef Matrix<double, 50, 1> myVector;

I want a third vector vectorThree that will have multiplication of vectorOne and vectorTwo. But I want to multiply each element by corresponding element - i.e. vectorOne(i, 0) by vectorTwo (i, 0) so that I have something like below for all i.

vectorThree (i, 0) = vectorOne(i, 0) * vectorTwo(i, 0)

I saw this and tried vectorOne.array() * vectorTwo.array() but it did not work.

I know I can do that using a for loop and iterating over all elements. But is there a more efficient or built in Eigen function for that?

Upvotes: 2

Views: 7428

Answers (2)

Subhendu Chakraborty
Subhendu Chakraborty

Reputation: 59

You can take advantage of asDiagonal() feature in Eigen library.

https://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#title15

So, for your case:

vectorOne.asDiagona()*vectorTwo

Should do the job.

Remember: "This is only for vectors (either row-vectors or column-vectors), i.e. matrices which are known at compile-time to have either one row or one column."

Upvotes: 1

R2RT
R2RT

Reputation: 2146

  1. You should be able to cast matrices to arrays via .array() and multiply it here. It would return an array expression though, so maybe it is not what you want.

From Eigen documentation:

First of all, of course you can multiply an array by a scalar, this works in the same way as matrices. Where arrays are fundamentally different from matrices, is when you multiply two together. Matrices interpret multiplication as matrix product and arrays interpret multiplication as coefficient-wise product. Thus, two arrays can be multiplied if and only if they have the same dimensions.

  1. Otherwise you can use .cwiseProduct of matrix to get matrix as result. https://eigen.tuxfamily.org/dox/group__QuickRefPage.html#matrixonly

Upvotes: 4

Related Questions