C++實現矩陣對稱正交化的示例代碼

1.python代碼

import numpy as np
import pandas as pd
df=pd.DataFrame()
df['fac_01']=(34, 45, 65)
df['fac_02']=(56, 25, 94)
print(df)
print('------------------矩陣的特征跟D、和特征向量U-----------------------')
D,U=np.linalg.eig(np.dot(df.T, df)) # 求矩陣的特征跟D、和特征向量U
print(D,U,sep='\n')
print('\n------------------對角矩陣-----------------------')
print(np.diag(D**(-0.5)))
print('\n------------------對稱正交後的矩陣-----------------------')
S = np.dot(np.dot(U, np.diag(D**(-0.5))), U.T) # 求過渡矩陣S = U* DEx *U'
F_hat = np.dot(df, S) # 求對稱正交後的矩陣
print(F_hat)

2.C++的Eigen庫實現

#include "Eigen/Dense"
using namespace Eigen;
int main()
{
    //初始化
    MatrixXf A(3, 2);
    A(0,0) = 34;A(0,1) = 56;
    A(1,0) = 45;A(1,1) = 25;
    A(2,0) = 65;A(2,1) = 94;
    //生成正交矩陣
    MatrixXf AEx = A.transpose() * A;
    int nRowSize = AEx.rows();
    int nColSize = AEx.cols();
    //求特征根、特征向量
    SelfAdjointEigenSolver<Matrix2f> eigensolver(AEx);
    MatrixXf D = eigensolver.eigenvalues();
    MatrixXf U = eigensolver.eigenvectors();
    std::cout<<"特征根如下:" <<std::endl;
    nRowSize = D.rows();
    nColSize = D.cols();
    for(size_t i=0; i<nRowSize; i++)
    {
        for(size_t j=0; j<nColSize; j++)
        {
            std::cout<<D(i,j)<<"    ";
        }
        std::cout<<std::endl;
    }
    std::cout<<"特征向量如下:" <<std::endl;
    nRowSize = U.rows();
    nColSize = U.cols();
    for(size_t i=0; i<nRowSize; i++)
    {
        for(size_t j=0; j<nColSize; j++)
        {
            std::cout<<U(i,j)<<"    ";
        }
        std::cout<<std::endl;
    }
    //生成np.diag(D**(-0.5)))對角線矩陣
    MatrixXf DEx(2,2);
    for(size_t i=0; i<2; i++)
    {
        for(size_t j=0; j<2; j++)
        {
            if(i == j)
            {
                DEx(i,j) = pow(D(i,0),-0.5);
            }
            else
            {
                DEx(i,j) = 0;
            }
        }
    }
    nRowSize = DEx.rows();
    nColSize = DEx.cols();
    std::cout<<"對角線矩陣如下:" <<std::endl;
    for(size_t i=0; i<nRowSize; i++)
    {
        for(size_t j=0; j<nColSize; j++)
        {
            std::cout<<DEx(i,j)<<"    ";
        }
        std::cout<<std::endl;
    }
    //生成過度矩陣S
    MatrixXf S = U * DEx * U.transpose();
    //生成正交化矩陣
    MatrixXf R = A * S;
    nRowSize = R.rows();
    nColSize = R.cols();
    std::cout<<"正交化結果如下:" <<std::endl;
    for(size_t i=0; i<nRowSize; i++)
    {
        for(size_t j=0; j<nColSize; j++)
        {
            std::cout<<R(i,j)<<"    ";
        }
        std::cout<<std::endl;
    }
	return 0;
}

3.結果對比

在這裡插入圖片描述

到此這篇關於C++實現矩陣對稱正交化的文章就介紹到這瞭,更多相關C++矩陣對稱正交化內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: