码迷,mamicode.com
首页 > 其他好文 > 详细

线性方程组的迭代解法——最速下降法

时间:2019-12-30 14:35:44      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:lse   max   bsp   for   desc   style   clear   end   解法   

  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
>> 

  

 

线性方程组的迭代解法——最速下降法

标签:lse   max   bsp   for   desc   style   clear   end   解法   

原文地址:https://www.cnblogs.com/guliangt/p/12119276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!