A=zeros(N^2)
for i=1:N^2
A(i,i)=4
if i+N<N^2+1
A(i,i+N)=-1
A(i+N,i)=A(i,i+N)
end
if mod(i,N)~=0
A(i,i+1)=-1
A(i+1,i)=A(i,i+1)
end
end
function x=cg(a,b,x)
%共轭向量法求解线性方程组
% 初始输入变量 a:系数矩阵 b:方程右端向量 x 输入的初始解
n=length(b)
r=b-a*x
p=r
q0=r'*r
while q0>1e-10
w=a*p
t=q0/(p'*w)
x=x+t*p
r=r-t*w
q=r'*r
s=q/q0
p=r+s*p
q0=q
end
通常最优化的教材后面都会附有程序吧%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=%4depsm=%9.3e \n',k,stopc)end
end
toc
time=toc
% fprintf('The iterations is %4d',k)
共轭梯度法是介于最速下降法与牛顿法之间的一个方法,它仅需利用一阶导数信息,但克服了最速下降法收敛慢的缺点,又避免了牛顿法需要存储和计算Hesse矩阵并求逆的缺点,共轭梯度法不仅是解决大型线性方程组最有用的方法之一,也是解大型非线性最优化最有效的算法之一。 共轭梯度法最早是又Hestenes和Stiefle(1952)提出来的,用于解正定系数矩阵的线性方程组,在这个基础上,Fletcher和Reeves(1964)首先提出了解非线性最优化问题的共轭梯度法。由于共轭梯度法不需要矩阵存储,且有较快的收敛速度和二次终止性等优点,现在共轭梯度法已经广泛地应用与实际问题中。 共轭梯度法是一个典型的共轭方向法,它的每一个搜索方向是互相共轭的,而这些搜索方向d仅仅是负梯度方向与上一次迭代的搜索方向的组合,因此,存储量少,计算方便欢迎分享,转载请注明来源:内存溢出
评论列表(0条)