我是靠谱客的博主 震动黄豆,这篇文章主要介绍Matlab迭代算法实现,现在分享给大家,希望可以做个参考。

牛顿迭代法

雅可比迭代法


高斯赛德迭代法


超松弛迭代法(SOR)


共轭迭代法

牛顿迭代法

代码实现案例:

复制代码
1
2
3
4
5
6
%% 原函数输入 function y = newton(x) y = exp(-x/4)*(2-x)-1;%任意函数 end % 保存要进行牛顿迭代的函数
复制代码
1
2
3
4
5
6
7
8
% 牛顿迭代函数生成 function y = newton1(x) syms a; f = a - (newton(a)./diff(newton(a))); y = subs(f,x);%牛顿迭代公式 end %如果直接用y和x来实现的话,在掉用原函数的时候就算出了具体数值,公式中的求导就会变为0, % 无法求解,所以先用f,a来代替y和x,最后再进行替换,实现牛顿迭代公式。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
% 牛顿迭代 x = input('x=');%开始迭代最初的x eps = input('eps=');%定义所要求解的精度 syms x1;%定义两Xk+1和Xk的差,一次来限制精度的要求 x1=100; syms xa; xa=x; syms xb;%记录上一个x和下一个x while x1>eps xb = xa; xa = newton1(xb); x1 = abs(xa-xb);%得到▲x end disp('该函数符合规定精度的解是:'); double(xa) % xa即为所求的值

Jacobi 迭代法函数

代码实现案例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function [x,y] = Jacobi(n, A ,b) %y = zeros(1000,1); eps = 1.0e-6; D = diag(diag(A)); L = -tril(A, -1); U = -triu(A, 1); B = D(L+U); f = Db; count = 1; x0 = zeros(n,1); x = B*x0 + f; tic; while norm(x-x0)> eps x0 = x; %y(count) = norm(x-Ab); x = B*x0 + f; count = count + 1; if count > 2000 disp('error:该矩阵不收敛'); return; end end toc; y = toc; disp(count); end

Gauss-Seidel 迭代法函数

代码实现案例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function [x, y]= Gauss_Seidel(n, A ,b) %y = zeros(1000,1); eps = 1.0e-6; D = diag(diag(A)); L = -tril(A, -1); U = -triu(A, 1); B = (D - L)U; f = (D - L)b; count = 1; x0 = zeros(n,1); x = B*x0 + f; tic; while norm(x-x0) > eps x0 = x; % y(count) = norm(x-Ab); x = B*x0 + f; count = count + 1; if count > 2000 disp('error:该矩阵不收敛'); return; end end toc; y = toc; disp(count); end

逐次超松弛迭代法函数

代码实现案例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function [x, y] = SOR(n, A ,b, w) y = zeros(1000,1); eps = 1.0e-6; D = diag(diag(A)); L = -tril(A, -1); U = -triu(A, 1); B = (D - w*L) ((1-w) * D + w*U); f = w * inv(D - w*L) * b; count = 1; x0 = zeros(n,1); x = B*x0 + f; tic; while norm(x-x0) > eps x0 = x; y(count) = norm(x-Ab); x = B*x0 + f; count = count + 1; if count > 2000 disp('error:该矩阵不收敛'); return; end end toc; y = toc; disp(count); end

共轭梯度法函数

代码实现案例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function [x, y] = CG(n, A , b) y = zeros(1000,1); eps = 1.0e-6; x0 = zeros(n,1); r0 = b - A * x0; p0 = r0; count = 1; tic; while norm(p0) > eps a = r0'*r0/(p0'*A*p0); x = x0 + a*p0; r = r0 - a*A*p0; B = r'*r/(r0'*r0); p = r + B*p0; p0 = p; r0 = r; x0 = x; % y(count) = norm(x-Ab); count = count + 1; if count > 2000 disp('error:该矩阵不收敛'); return; end end toc; y = toc; disp(count); end

最后

以上就是震动黄豆最近收集整理的关于Matlab迭代算法实现的全部内容,更多相关Matlab迭代算法实现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(101)

评论列表共有 0 条评论

立即
投稿
返回
顶部