Product Point Column in Eigen C ++

Is there a simple way to evaluate the product of a column with a cloudy point from 2 matrices (let's call them A and B type Eigen::MatrixXd ) with dimensions mxn without estimating A*B or without resorting to for loops? The resulting vector must be 1xn or nx1 . Also, I am trying to do this with Eigen in C ++

+6
source share
3 answers

There are many ways to achieve this, all lazy grades:

 res = (A.array() * B.array()).colwise().sum(); res = (A.cwiseProduct(B)).colwise().sum(); 

And my favorite:

 res = (A.transpose() * B).diagonal(); 
+9
source

Here is how I would do it with Eigen::Map (assuming that real matrices can be expanded to complex using conjugate), where rows and cols denote the number of rows / columns:

 #include <Eigen/Dense> #include <iostream> int main() { Eigen::MatrixXd A(2, 2); Eigen::MatrixXd B(2, 2); A << 1, 2, 3, 4; B << 5, 6, 7, 8; int rows = 2, cols = 2; Eigen::VectorXd vA = Eigen::Map<Eigen::VectorXd>( const_cast<double *>(A.data()), rows * cols, 1); Eigen::VectorXd vB = Eigen::Map<Eigen::VectorXd>( const_cast<double *>(B.data()), rows * cols, 1); double inner_prod = (vA.transpose() * vB).sum(); std::cout << inner_prod << std::endl; } 
0
source

I did an experiment based on @ggael's answer.

 MatrixXd A = MatrixXd::Random(600000,30); MatrixXd B = MatrixXd::Random(600000,30); MatrixXd res; clock_t start, end; start = clock(); res.noalias() = (A * B.transpose()).diagonal(); end = clock(); cout << "Dur 1 : " << (end - start) / (double)CLOCKS_PER_SEC << endl; MatrixXd res2; start = clock(); res2 = (A.array() * B.array()).rowwise().sum(); end = clock(); cout << "Dur 2 : " << (end - start) / (double)CLOCKS_PER_SEC << endl; MatrixXd res3; start = clock(); res3 = (A.cwiseProduct(B)).rowwise().sum(); end = clock(); cout << "Dur 3 : " << (end - start) / (double)CLOCKS_PER_SEC << endl; 

And the conclusion:

 Dur 1 : 10.442 Dur 2 : 8.415 Dur 3 : 7.576 

The diagonal () solution seems to be the slowest. CwiseProduct is one of the fastest. And memory usage is the same.

0
source

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


All Articles