matlab写出所有作业代码
时间: 2024-12-17 19:52:38 浏览: 10
根据提供的文档内容,以下是需要编写的MATLAB作业代码:
### 1. Gauss消去法 (Gauss Elimination Method)
```matlab
function x = Demo_4_1_Gauss_S(A, b)
n = length(b);
% 增广矩阵
Ab = [A b];
% 消元过程
for k = 1:n-1
for i = k+1:n
factor = Ab(i,k) / Ab(k,k);
Ab(i,k:n+1) = Ab(i,k:n+1) - factor * Ab(k,k:n+1);
end
end
% 回代求解
x = zeros(n,1);
x(n) = Ab(n,n+1) / Ab(n,n);
for i = n-1:-1:1
x(i) = (Ab(i,n+1) - Ab(i,i+1:n) * x(i+1:n)) / Ab(i,i);
end
end
```
### 2. 杜立特尔分解法 (Doolittle Decomposition)
```matlab
function [L, U] = Demo_4_2_Doolittle(A)
n = size(A, 1);
L = eye(n);
U = zeros(n);
for k = 1:n
U(k,k) = A(k,k) - L(k,1:k-1) * U(1:k-1,k);
for j = k+1:n
U(k,j) = A(k,j) - L(k,1:k-1) * U(1:k-1,j);
end
for i = k+1:n
L(i,k) = (A(i,k) - L(i,1:k-1) * U(1:k-1,k)) / U(k,k);
end
end
end
```
### 3. 逐次超松弛迭代法 (Successive Over-Relaxation Iteration Method)
```matlab
function x = Demo_6_2_Jacobi_G_S_SOR(A, b, w, tol, max_iter)
n = length(b);
x = zeros(n, 1); % 初始猜测
x_new = zeros(n, 1);
iter = 0;
while true
iter = iter + 1;
for i = 1:n
sigma = 0;
for j = 1:n
if j ~= i
sigma = sigma + A(i,j) * x(j);
end
end
x_new(i) = (1 - w) * x(i) + (w / A(i,i)) * (b(i) - sigma);
end
if norm(x_new - x, inf) < tol || iter >= max_iter
break;
end
x = x_new;
end
end
```
### 使用示例
假设你需要解以下线性方程组:
\[ \begin{cases}
2x_1 + 3x_2 + 4x_3 = 6 \\
3x_1 + 5x_2 + 2x_3 = 5 \\
4x_1 + 3x_2 + 30x_3 = 32
\end{cases} \]
可以调用上述函数如下:
```matlab
% 定义系数矩阵和常数向量
A = [2 3 4; 3 5 2; 4 3 30];
b = [6; 5; 32];
% 调用Gauss消去法
x_gauss = Demo_4_1_Gauss_S(A, b);
% 调用杜立特尔分解法
[L, U] = Demo_4_2_Doolittle(A);
y = L \ b;
x_doolittle = U \ y;
% 调用逐次超松弛迭代法
w = 1.2; % 超松弛因子
tol = 1e-6; % 容差
max_iter = 1000; % 最大迭代次数
x_sor = Demo_6_2_Jacobi_G_S_SOR(A, b, w, tol, max_iter);
disp('Gauss消去法结果:');
disp(x_gauss);
disp('杜立特尔分解法结果:');
disp(x_doolittle);
disp('逐次超松弛迭代法结果:');
disp(x_sor);
```
以上是根据文档内容编写的MATLAB代码,希望对你有帮助!
阅读全文