[MATLAB]Jacobi迭代

[MATLAB代码]关于使用雅可比迭代法求线性方程组的数值解

jacobi.m
%定义Jacobi迭代函数
function [x, n] = jacobi(A, b, x0, eps)
%计算迭代矩阵
D = diag(diag(A));
L = -tril(A,-1);
U = -triu(A,1);
BJ = D\(L+U);
f = D\b;
%判断收敛性
a = max(abs(eig(BJ)));
if a >= 1
    disp('Jacobi迭代不收敛');
    return             %不再向下执行
else
    n = 1;
    x = BJ*x0 + f;
    while norm(x-x0,inf)>=eps   %无穷范数
        x0 = x;
        x = BJ*x0+f;
        n = n+1;
    end
end

A = [4 3 0; 3 4 -1; 0 -1 4];
b = [24; 30; -24];
x0 = [0; 0; 0];
eps = 1.0e-6;
[x, n] = jacobi(A,b,x0,eps);

你可能感兴趣的:(MATLAB,matlab,算法)