clc A = [4 -2 -1; -2 -4 -2; -1 -2 3];%矩阵 b = [0, -2 , 3]';% 右端项 x0 = [1,1,1]'; [x,k] = SOR(A,b,x0,1.45,1e-6) % % max_iter: 最大迭代步数 % % n=28; % tol = 1.0e-8; % w = 1.45; % 松弛因子 % x0 = [1,1,1]'; % for i = 1:n % [x, n] = SOR(A, b, x0,w,i) % fprintf('第%d次sor_%.2f迭代计算的结果:\n',n-1,w); % disp(x); % end function [x, k] = SOR(A, b, x0,w,tol) max=300; D = diag(diag(A));%求A的对角矩阵 L =-tril(A,-1);%求A的下三角矩阵 U =-triu(A,1);%求A的上三角矩阵 B = inv(D-L*w)*((1-w)*D+w*U); f = w*inv((D-L*w))*b; x = B*x0+f; k = 1; while norm(x-x0)>=tol x0 = x; x = B*x0+f; k = k+1; if(k>=max) disp('迭代次数超过',max1,'次,方程组可能不收敛'); return; end end [k,x'] end出错 hw2>SOR (第 32 行) disp('迭代次数超过',max1,'次,方程组可能不收敛'); 出错 hw2 (第 5 行) [x,k] = SOR(A,b,x0,1.45,1e-6
时间: 2024-03-11 08:48:25 浏览: 66
这个程序中,存在一个语法错误和一个逻辑错误。
语法错误在 SOR 函数中,在输出提示信息时,使用了错误的变量名 max1,应该改为 max。
逻辑错误在 SOR 函数中,当迭代次数超过最大迭代步数 max 时,程序并没有直接返回结果,而是输出了提示信息后继续运行,导致程序出错。应该在输出提示信息后加一个 return 语句来结束函数的运行。
以下是修改后的程序:
```
clc
A = [4 -2 -1; -2 -4 -2; -1 -2 3];
b = [0, -2 , 3]';
x0 = [1,1,1]';
[x,k] = SOR(A,b,x0,1.45,1e-6)
% max_iter: 最大迭代步数
% n=28;
% tol = 1.0e-8;
% w = 1.45; % 松弛因子
% x0 = [1,1,1]';
% for i = 1:n
% [x, n] = SOR(A, b, x0,w,i)
% fprintf('第%d次sor_%.2f迭代计算的结果:\n',n-1,w);
% disp(x);
% end
function [x, k] = SOR(A, b, x0, w, tol)
max = 300;
D = diag(diag(A)); % 求A的对角矩阵
L = -tril(A,-1); % 求A的下三角矩阵
U = -triu(A,1); % 求A的上三角矩阵
B = inv(D-L*w)*((1-w)*D+w*U);
f = w*inv((D-L*w))*b;
x = B*x0+f;
k = 1;
while norm(x-x0) >= tol
x0 = x;
x = B*x0+f;
k = k+1;
if k >= max
disp('迭代次数超过最大迭代步数,方程组可能不收敛');
return;
end
end
[k,x']
end
```
阅读全文
相关推荐











clc;clear; data=xlsread('C:\Users\86186\Desktop\数字建模\第五次数据','B2:E21'); %%%第一步:数据预处理——数据正向化 %(注:含氧量越高越好;PH值越接近7越好;细菌总数越少越好;植物性营养物量介于10‐20 %之间最佳,超过20或低于10均不好。) %含氧量越高越好, 极大型 ,数据不变 %PH值越接近7越好, 中间型指标 x_best=7; data(:,2)=1-abs(data(:,2)-x_best)./max(abs(data(:,2)-x_best)); %细菌总数越少越好, 极小型 data(:,3)=max(data(:,3)-data(:,3)); %植物性营养物量介于10‐20 %之间最佳,超过20或低于10均不好。 区间型 a=10;b=20; M=max(a-min(data(:,4)),max(data(:,4)-b)); n=size(data,1); for i=1:n if data(i,4)b data(i,4)=1-(data(i,4)-b)/M; else data(i,4)=1; end end %%%第二部:正向矩阵标准化 %求权重 data=data./sqrt(sum(data.^2)); %%第三步:计算各指标权重 w=shangquan(data); %%%%%第四步:计算得分并排序 %用TOPSIS计算得分并排序 %定义第i个评价对象与正理想的距离 D1=sqrt((max(data)-data).^2*w'); %定义第i个评价对象与负理想的距离 D2=sqrt((min(data)-data).^2*w'); %计算得出第i个评价对象的得分∶ score=D2./(D1+D2); [ss,ind]=sort(score,'descend');








