雅可比迭代法matlab代码
时间: 2023-09-04 19:16:24 浏览: 136
MATLAB选题
以下是雅可比迭代法的 MATLAB 代码示例:
```matlab
function [x, k] = jacobi(A, b, x0, tol, maxit)
% Jacobi Iteration Method
% A: coefficient matrix
% b: right-hand side vector
% x0: initial guess
% tol: tolerance
% maxit: maximum number of iterations
n = length(b); % dimension of the system
x = x0; % initialize x
for k = 1:maxit
for i = 1:n
sigma = 0;
for j = 1:n
if j ~= i
sigma = sigma + A(i,j)*x(j);
end
end
x(i) = (b(i) - sigma)/A(i,i);
end
if norm(A*x - b) < tol % check convergence
return;
end
end
warning('Maximum number of iterations reached without convergence.');
end
```
其中,输入参数为:
- `A`:系数矩阵;
- `b`:右侧向量;
- `x0`:初始猜测向量;
- `tol`:收敛阈值;
- `maxit`:最大迭代次数。
输出参数为:
- `x`:解向量;
- `k`:迭代次数。
阅读全文