1.代码
%%雅可比迭代法(此迭代法对于病态矩阵的解不理想) %%线性方程组M*X = b,M是方阵,X0是初始解向量,epsilon是控制精度 function JIM = Jacobian_iteration_method(M,b,X0,epsilon) [m,n] = size(M); d = diag(M);L = zeros(m,n);U = zeros(m,n);D = zeros(m,n); delta = 0;ub = 100;X = zeros(m,ub);X(:,1) = X0;X_delta = X;X_end = zeros(m,1);k_end = 0;k = 1;e = floor(abs(log(epsilon))); for i = 1:1:m for j = 1:1:n if i > j L(i,j) = -M(i,j); elseif i < j U(i,j) = -M(i,j); elseif i == j D(i,j) = d(i); end end end B = inv(D)*(L+U); f = inv(D)*b; X_real = inv(M)*b; for k = 1:1:ub X_delta(:,k) = X(:,k)-X_real; delta = norm(X_delta(:,k),2); if delta < epsilon break end X(:,k+1) = B*X(:,k)+f; end disp(‘迭代次数为:‘); k disp(‘迭代解为:‘); JIM=vpa([X(:,k)],e); end
2.例子
clear all clc for i = 1:8 for j = 1:8 if i == j M(i,j) = 2.1; elseif i - j == 1 M(i,j) = 1; elseif j - i == 1 M(i,j) = -1; else M(i,j) = 0; end end end b = [1 2 3 4 4 3 2 1]‘; X0 = [1 1 1 1 1 1 1 1]‘; epsilon = 1e-4; S = Jacobian_iteration_method(M,b,X0,epsilon) M\b
结果为
迭代次数为: k = 73 迭代解为: S = 1.07162282 1.25046562 1.69755831 1.81519199 1.50952631 0.985363364 0.57873237 0.200592913 ans = 1.0716 1.2504 1.6975 1.8152 1.5096 0.9853 0.5787 0.2006
原文地址:https://www.cnblogs.com/guliangt/p/12119352.html
时间: 2024-11-12 20:29:17