I would like to multiply the columns of matrix A to vector v and finally get the sum of each column. I use Eigen library and coded as follows:
for (int j = 0 ; j< A.cols(); j++)
C.col(j).noalias() = V.cwiseProduct(A.col(j));
V2 = C.colwise().sum();
However, it is still slow. I also used the following products but these are even slower.
1. C = A * V.asDiagonal();
2. C = A.array().rowwise() * V.transpose().array();
Any idea?
Hm... what you're looking for is a plain standard vector-matrix product:
V2.noalias() = V.transpose() * A;
The .noalias()
is optional, it's only here to save you one temporary.
If you really need the intermediate matrix C
, then your two options should be equally fast as your hand-crafted for loop provided that you correct them to make them compute the same thing:
C = V.asDiagonal() * A;
C = A.array().colwise() * V.array();
And don't forget to enable compiler optimizations, eg -O3 -march=native
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.