functionA=OMP(D,X,L)%输入参数:%D-过完备字典,注意:必须字典的各列必须经过了规范化%X-信号%L-系数中非零元个数的最大值(可选,默认为D的列数,速度可能慢)%输出参数:%A-稀疏系数ifnargin==2L=size(D,2);endP=size(X,2);K=size(D,2);fork=1:1:P,a=[];x=X(:,k);residual=x;indx=zeros(L,1);forj=1:1:L,proj=D'*residual;[maxVal,pos]=max(abs(proj));pos=pos(1);indx(j)=pos;a=pinv(D(:,indx(1:j)))*x;residual=x-D(:,indx(1:j))*a;ifsum(residual.^2)1e-6break;endend;temp=zeros(K,1);temp(indx(1:j))=a;A(:,k)=sparse(temp);end;return;function[A,x]=KSVD(y,codebook_size,errGoal)%==============================%inputparameter%y-inputsignal%codebook_size-countofatoms%outputparameter%A-dictionary%x-coefficent%reference:K-SVD:AnAlgorithmforDesigningofOvercompleteDictionaries%forSparseRepresentation,AharonM.,EladM.etc%==============================if(size(y,2)codebook_size)disp('codebook_sizeistoolargeortrainingsamplesistoosmall');%显示””return;end%initialization[rows,cols]=size(y);%y的行、列数目分别赋值给rows、colsr=randperm(cols);%r为维度为cols的随机置换向量A=y(:,r(1:codebook_size));%将y的第(r的第1个到第“原子个数个”数)列提取出构成初始字典AA=A./repmat(sqrt(sum(A.^2,1)),rows,1);ksvd_iter=10;fork=1:ksvd_iter%sparsecodingifnargin==2x=OMP(A,y,5.0/6*rows);elseifnargin==3x=OMPerr(A,y,errGoal);end%updatedictionaryform=1:codebook_sizemindex=find(x(m,:));if~isempty(mindex)%若mindex为空矩阵,则返回0mx=x(:,mindex);mx(m,:)=0;my=A*mx;resy=y(:,mindex);mE=resy-my;[u,s,v]=svds(mE,1);A(:,m)=u;x(m,mindex)=s*v';endendend