%本函数用于计算n*n方阵的最佳松弛因子
%本函数只能求解当A为n*n的矩阵
%用步长为0.01扫描w的取值区间0-2
%2010-10-23
function [bw,brho]=BSOR(A)
n=max(size(A));
D=zeros(n,n);
L=zeros(n,n);
U=zeros(n,n);%初始化三个矩阵
rho=zeros(199,1);
%获取三个矩阵D,L,U
for i=1:n
for j=1:n
if i>j
L(i,j)=A(i,j);
elseif i<j
U(i,j)=A(i,j);
else
D(i,j)=A(i,j);
end
end
end
for i=1:199
w=i/100;
G=-inv(D/w+L)*((1-1/w)*D+U);%计算迭代矩阵
rho(i)=max(abs(eig(G)));%求每一个迭代矩阵的谱半径
end
t=0;
brho=rho(1);
for i=1:199
if brho>rho(i)
t=i;
brho=rho(i);
end
end
bw=t/100;
aw=0.01:0.01:1.99;
plot(aw,rho);
grid;
xlabel('松弛因子w');
ylabel('谱半径rho');
title('rho-w关系图');
end