欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现矩阵对称正交化的示例代码

程序员文章站 2022-06-15 12:02:40
1.python代码import numpy as npimport pandas as pddf=pd.dataframe()df['fac_01']=(34, 45, 65)df['fac_02'...

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++实现矩阵对称正交化的文章就介绍到这了,更多相关c++矩阵对称正交化内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!