发布网友
共1个回答
热心网友
通常最优化的教材后面都会附有程序吧
%Function of the CG method
%What should be inputed are the start point 'xstart',
% the matrix A,vector b and tol.
% It would give the solution x ,iterations and the iterative time
function [time,k,x]=normCG(xstart,A,b,tol)
x=xstart; Fx=0.5*x'*A*x-b'*x;
tol=10^(-6); beta=1;
r=A'*xstart-b; %r0
p=-r; %p0
stopc=norm(r,inf);
k=0;
tic;
while(stopc>tol && k<=2000)
r0=r;
p0=p;
rpinfang=r0'*r0; %r(k)^2
fenmu=p0'*A*p0;
alpha=rpinfang/fenmu; %alpha
x=x+alpha*p0; %x(k+1)
r=r0+alpha*A*p0; %r(k+1)
beta=(r'*r)/rpinfang; %beta
p=-r+beta*p0; %p(k+1)
stopc=norm(r,inf);
k=k+1;
if mod(k,10)==0 fprintf(' k=%4d epsm=%9.3e \n',k,stopc); end;
end
toc;
time=toc;
% fprintf('The iterations is %4d',k);