• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

MATLAB实现矩阵雅可比(Jacobi)迭代

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

包含三个function,下列代码最后一段是主函数,其他都是function。三个function建议从下往上看。

function [x,k,resvec,DD,ID,JD,D,Ab] = jacobis(AA,IA,JA,b,x,tol,kmax)

%This function is an implementation of Jacobi’s
%iterative method for solving Ax=b.
%The input vector x is the initial guess, while tol
%is the tolerance used for stopping the iteration; kmax is the
%maximum number of iterations to be run. The output is the kth
%approximation to the exact solution, while resvec is a vector
%containing the 2-norms of the residual vectors.
n=length(b);
if ~exist(‘x’), x=zeros(n,1);end
if ~exist(‘tol’), tol=1e-6;end
if ~exist(‘kmax’), kmax=1e4;end

r=b-matvecs(AA,IA,JA,x);
res0=norm®;res=norm®;
resvec=res/res0;res=1;k=0;
%extract a vector D containing the main diagonal of matrix A
[DD,ID,JD]=diags(AA,IA,JA);
D=zeros(ID(end),1);
for i =1:length(DD)
D(ID(i))=D(ID(i))+DD(i);
end
while res>tol & k<kmax
k=k+1;
z=r./D;
x=x+z;
r=b-matvecs(AA,IA,JA,x);
res=norm®/res0;
resvec=[resvec res];
fprintf(’%2.9f\t %3d\n’,resvec(end),k)
end
%-----------------------------------------------------------
function w=matvecs(AA,IA,JA,v)

%Sparse matrix-vector product c=A*v: the matrix is provided
%in coordinate format AA, IA, JA, with m=IA(end), n=JA(end).
%The input vector v is assumed to be full.
%The output vector w is assumed to be full.

ma=IA(end);na=JA(end);nb=length(v);
if na~=nb,error(‘Wrong sizes: cannot perform matrix-vector product’);end

w=zeros(ma,1);
for k=1:length(AA)
w(IA(k))=w(IA(k))+AA(k)*v(JA(k));%edit this line to provide the correct expression for w
end
%------------------------------------------------------------
function [DD,ID,JD]=diags(AA,IA,JA)

%Jacobi splitting:
%Input: sparse matrix A in coordinate format (AA, IA, JA)
%Output: sparse diagonal matrix D in coordinate format (DD, ID, JD)
diag_values=[];
diag_row_index=[];
diag_col_index=[];
for k=1:length(AA)
if IA(k)==JA(k)
diag_row_index=[diag_row_index;IA(k)];
diag_col_index=[diag_col_index;JA(k)];
diag_values=[diag_values;AA(k)];
end
end
DD=diag_values;
ID=[diag_row_index;IA(end)];
JD=[diag_col_index;JA(end)];

n=100;
e = ones(n,1);
A = spdiags([-e 4*e -e], -1:1, n, n);
[IA,JA,AA]=find(A);
IA=[IA;n];JA=[JA;n];
[x,k,resvec] = jacobis(AA,IA,JA,e);


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap