4

我有以下代码:

Eigen::MatrixXf aMatrix( 3, 5 );
aMatrix <<
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 1, 1, 1, 1;

Eigen::VectorXf aVector( 5 );
aVector << 3, 4, 5, 6, 7;

cout << aMatrix.cwiseProduct( aVector.replicate( 1, aMatrix.rows() ).transpose() ) << endl;

输出:

3 0 5 0 7
0 4 0 6 0
3 4 5 6 7

有没有比使用replicate()调用更有效的方法来实现这一点?

4

2 回答 2

5

已解决(借助:如何在 Eigen 应用类似 bsxfun 的功能?

这些是等价的:

aMatrix.cwiseProduct( aVector.replicate( 1, aMatrix.rows() ).transpose() )
aMatrix.array().rowwise() * aVector.array().transpose()
于 2014-08-25T19:59:16.650 回答
2

我不确定这是否更有效,但后乘以对角矩阵是另一种选择。

aMatrix * aVector.asDiagonal();

#include <iostream>
#include <Eigen/Dense>    

int main()
{

  Eigen::MatrixXf aMatrix( 3, 5 );
  aMatrix <<
    1, 0, 1, 0, 1,
    0, 1, 0, 1, 0,
    1, 1, 1, 1, 1;

  Eigen::VectorXf aVector( 5 );
  aVector << 3, 4, 5, 6, 7;

  std::cout << aMatrix * aVector.asDiagonal() << std::endl;

  return 0;
}
于 2014-09-07T02:02:40.660 回答