1.代码
%%最速下降法(用于求解正定对称方程组) %%线性方程组M*X = b,M是方阵,X0是初始解向量,epsilon是控制精度 function TSDM = The_steepest_descent_method(M,b,X0,epsilon) m = size(M);up = 1000;e = floor(abs(log(epsilon))); X(:,1) = X0; r(:,1) = b-M*X0; for k = 1:up alpha = Inner_product(r(:,k),r(:,k))/Inner_product(M*r(:,k),r(:,k)); X(:,k+1) = X(:,k)+alpha*r(:,k); r(:,k+1) = b-M*X(:,k+1); X_delta(:,k) = X(:,k+1)-X(:,k); if sqrt(Inner_product(X_delta(:,k),M*X_delta(:,k))) < epsilon break; end end disp(‘迭代次数为:‘); k-1 TSDM = vpa(X(:,k),e); %%内积 function IP = Inner_product(M1,M2) MAX = max(size(M1)); sum = 0; for i = 1:MAX sum = sum+M1(i)*M2(i); end IP = sum; end end
2.例子
clear all clc for i = 1:4 for j = 1:4 if i == j M(i,j) = 2.1; else M(i,j) = 1.5; end end end b = [1 2 3 4]‘; X0 = [1 1 1 1]‘; epsilon = 1e-4; S = The_steepest_descent_method(M,b,X0,epsilon) M\b
结果为
迭代次数为: ans = 21 S = -2.12110743 -0.454511872 1.21208369 2.87867925 ans = -2.1212 -0.4545 1.2121 2.8788 >>
原文地址:https://www.cnblogs.com/guliangt/p/12119276.html
时间: 2024-10-11 08:55:17