matlab 高斯迭代代码_超松弛迭代法(SOR)
时间: 2023-07-28 09:10:15 浏览: 92
好的,这是一个 Matlab 的超松弛迭代法(SOR)的高斯迭代代码,可以用于解决线性方程组:
```matlab
function [x,iter]=SOR(A,b,x0,w,tol,maxiter)
% SOR(A,b,x0,w,tol,maxiter) uses the Successive Over-Relaxation method
% to solve the linear system Ax=b.
% Inputs:
% A is an n x n matrix
% b is an n x 1 vector
% x0 is an n x 1 vector representing the initial guess
% w is the relaxation parameter (default is w=1)
% tol is the tolerance for stopping criteria (default is tol=1e-6)
% maxiter is the maximum number of iterations (default is maxiter=100)
% Outputs:
% x is an n x 1 vector representing the solution
% iter is the number of iterations performed
% Check inputs and set default values
if nargin<3
error('At least three inputs are required.')
end
if nargin<4 || isempty(w)
w=1;
end
if nargin<5 || isempty(tol)
tol=1e-6;
end
if nargin<6 || isempty(maxiter)
maxiter=100;
end
% Initialize variables
n=length(b);
x=x0;
iter=0;
err=inf;
% Perform SOR iterations
while err>tol && iter<maxiter
xold=x;
for i=1:n
x(i)=(1-w)*xold(i)+w*(b(i)-A(i,1:i-1)*x(1:i-1)-A(i,i+1:n)*xold(i+1:n))/A(i,i);
end
iter=iter+1;
err=norm(x-xold)/norm(x);
end
% Display error message if maximum number of iterations is reached
if iter==maxiter && err>tol
warning('Maximum number of iterations reached without convergence.')
end
end
```
其中,A 为系数矩阵,b 为常数向量,x0 为初始解向量,w 为松弛因子,tol 为迭代停止的相对误差,maxiter 为最大迭代次数。
示例用法:
```matlab
% Example usage:
A=[4 -1 0 0; -1 4 -1 0; 0 -1 4 -1; 0 0 -1 3];
b=[15;10;10;10];
x0=[0;0;0;0];
w=1.25;
tol=1e-6;
maxiter=100;
[x,iter]=SOR(A,b,x0,w,tol,maxiter);
disp(['Solution: [',num2str(x.'),']'])
disp(['Number of iterations: ',num2str(iter)])
```
希望能对你有帮助!
阅读全文