奇异值分解(SVD) C++代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
/**
函数原型:
bool svd(vector
输入矩阵A,分解矩阵的秩K
输出U,S,V
本函数将A分解为U diag(S) V'
S[i],U[i],V[i]是A的第i大奇异值,及其对应的左歧义向量和右奇异向量
S,U,V的size由K指定
K是需要分解的rank,0
**/
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAX_ITER=100000;
const double eps=0.0000001;
double get_norm(double *x, int n){
double r=0;
for(int i=0;i
return sqrt(r);
}
double normalize(double *x, int n){
double r=get_norm(x,n);
if(r
for(int i=0;i
return r;
}
inline double product(double*a, double *b,int n){
double r=0;
for(int i=0;i
return r;
}
void orth(double *a, double *b, int n){//|a|=1
double r=product(a,b,n);
for(int i=0;i
}
bool svd(vector
int M=A.size();
int N=A[0].size();
U.clear();
V.clear();
S.clear();
S.resize(K,0);
U.resize(K);
for(int i=0;i
V.resize(K);
for(int i=0;i
srand(time(0));
double *left_vector=new double[M];
double *next_left_vector=new double[M];
double *right_vector=new double[N];
double *next_right_vector=new double[N];
while(1){
for(int i=0;i
if(normalize(left_vector, M)>eps)
break;
}
int col=0;
for(int col=0;col
double r=-1;
for(int iter=0;diff>=eps && iter
memset(next_right_vector,0,sizeof(double)*N);
for(int i=0;i
r=normalize(next_right_vector,N);
if(r
normalize(next_right_vector,N);
for(int i=0;i
r=normalize(next_left_vector,M);
if(r
normalize(next_left_vector,M);
diff=0;
for(int i=0;i
=next_left_vector[i]-left_vector[i];
diff+=d*d;
}
memcpy(left_vector,next_left_vector,sizeof(double)*M);
memcpy(right_vector,next_right_vector,sizeof(double)*N);
}
if(r>=eps){
S[col]=r;
memcpy((char *)&U[col][0],left_vector,sizeof(double)*M);
memcpy((char *)&V[col][0],right_vector,sizeof(double)*N);
}else
break;
}
delete [] next_left_vector;
delete [] next_right_vector;
delete [] left_vector;
delete [] right_vector;
return true;
}
void print(vector
for(int i=0;i
cout<
}
int main(){
int m=10;
int n=5;
srand(time(0));
vector
A.resize(m);
for(int i=0;i
for(int j=0;j
}
print(A);
cout<
vector
vector
svd(A,2,U,S,V);
cout<<"U="<
cout< }
cout<
return 0;
}