Column-wise dot product in Eigen C++

前端 未结 3 1997
不知归路
不知归路 2021-01-12 14:43

Is there an easy way to evaluate the column wise dot product of 2 matrices (lets call them A and B, of type Eigen::MatrixXd) that have

3条回答
  •  走了就别回头了
    2021-01-12 14:58

    Here is how I'd do it with an Eigen::Map (assuming real matrices, can extend to complex via taking the adjoint), where rows and cols denote the number of rows/columns:

    #include 
    #include 
    
    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(
                                 const_cast(A.data()), rows * cols, 1);
        Eigen::VectorXd vB = Eigen::Map(
                                 const_cast(B.data()), rows * cols, 1);
    
        double inner_prod = (vA.transpose() * vB).sum();
    
        std::cout << inner_prod << std::endl;
    }
    

提交回复
热议问题