从MATLAB diag(sqrt(v))转换为C ++中的Eigen

时间:2016-05-12 18:43:11

标签: c++ matlab matrix eigen

我有以下MATLAB片段,我想用C ++将其翻译成Eigen:

>> v=[1; 2; 3]
v =

   1
   2
   3

>> m=diag(sqrt(v))
m =

Diagonal Matrix

   1.0000        0        0
        0   1.4142        0
        0        0   1.7321

我的C ++代码如下:

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

int main()
{
    Eigen::Matrix< double, 3, 1> v;
    v << 1,2,3;
    std::cout << v << "\n";

    Eigen::Matrix< double, 3, 1> v2 = v.array().sqrt();
    Eigen::Matrix< double, 3, 3> m = v2.asDiagonal();

    std::cout << m << "\n";

    return 0;
}

输出结果为:

1
2
3
      1       0       0
      0 1.41421       0
      0       0 1.73205

所以它有效,但我不喜欢它,因为我更喜欢像

这样的东西
#include <iostream>
#include "Eigen/Dense"

int main()
{
    Eigen::Matrix< double, 3, 1> v;
    v << 1,2,3;
    std::cout << v << "\n";

    Eigen::Matrix< double, 3, 3> m = v.array().sqrt().asDiagonal();

    std::cout << m << "\n";

    return 0;
}

没有编译给出这个错误:

/home/aj/projects/test_eigen/test_eigen.cpp: In function ‘int main()’:
/home/aj/projects/test_eigen/test_eigen.cpp:10:52: error: ‘const class Eigen::CwiseUnaryOp<Eigen::internal::scalar_sqrt_op<double>, const Eigen::ArrayWrapper<Eigen::Matrix<double, 3, 1> > >’ has no member named ‘asDiagonal’
  Eigen::Matrix< double, 3, 3> m = v.array().sqrt().asDiagonal();
                                                    ^
CMakeFiles/test_eigen.dir/build.make:62: recipe for target 'CMakeFiles/test_eigen.dir/test_eigen.cpp.o' failed
make[2]: *** [CMakeFiles/test_eigen.dir/test_eigen.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/test_eigen.dir/all' failed
make[1]: *** [CMakeFiles/test_eigen.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

我可以获得单行

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

int main()
{
    Eigen::Matrix< double, 3, 1> v;
    v << 1,2,3;
    std::cout << v << "\n";

    Eigen::Matrix< double, 3, 3> m = Eigen::Matrix< double, 3, 1>(v.array().sqrt()).asDiagonal();

    std::cout << m << "\n";

    return 0;
}

但在我看来我仍然缺少一些东西,或者我不完全理解如何用Eigen正确编写代码......

1 个答案:

答案 0 :(得分:2)

以下内容应该有效,请注意.matrix()从ArrayWrapper转换回Matrix:

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

int main()
{
    Eigen::Matrix< double, 3, 1> v ;
    v << 1, 2, 3;
    Eigen::Matrix< double, 3, 3> m = v.array().sqrt().matrix().asDiagonal());

    std::cout << m << "\n";

    return 0;
}