保存为成员的 SelfAdjointEigenSolver 结果在另一个范围内重新初始化

Result of SelfAdjointEigenSolver saved as member is reinitialized when in another scope

我正在尝试 运行 特征矩阵块上的主成分分析。 输入矩阵中的观察值在列中。 我想将特征向量保存为矩阵以备后用。 但是矩阵 (m_pcaCoefs) "gets reinitialized" 当我在另一个范围内使用它时,当然在 class 内。

我很确定我遗漏了一些有关 eigen 工作原理的信息!

class foo {
    public:
    using InputMatrixType = Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>;

        void computePca(InputMatrixType & inputMatrix)
        {
            // m_pcaCoefs is a private member of dense matrix type
            size_t start = 1;
            auto r = inputMatrix.rows();
            auto c = inputMatrix.cols(); 
            Eigen::Block<InputMatrixType>  inputBlock 
                  = inputMatrix.block( start, 0 ,r-start , c   );

            // center the data
            m_pixelValueMeans = inputBlock.rowwise().mean();
            inputBlock.colwise() -= m_pixelValueMeans;

            // inputBlock is a d by n, where d is the number of observation
            InputMatrixType cov = inputBlock * inputBlock.adjoint();
            cov = cov / (c - 1);
            Eigen::SelfAdjointEigenSolver<InputMatrixType> eig(cov);
            InputMatrixType m_pcaCoefs = eig.eigenvectors();
            // here m_pcaCoefs looks fine
            std::cout << m_pcaCoefs.size() << std::endl; // output: 9  
        }

        void print()
        {
            std::cout << m_pcaCoefs.size() << std::endl; // output: 0
        }
    protected:
       InputMatrixType m_pcaCoefs;
}


int main()
{
    foo test;
    test.computePca(someMatrix); // outputs 9
    test.print() // output 0
}

知道如何将特征向量复制到 m_pcaCoefs 吗?

InputMatrixType m_pcaCoefs = eig.eigenvectors();

这不是你想的那样 class。

你应该只使用:

m_pcaCoefs = eig.eigenvectors(); // use member m_pcaCoefs