给出解线性方程组的列主元素高斯消去法和LU分解法的matlab代码
时间: 2024-01-30 16:01:50 浏览: 80
列主元素高斯消去法的 MATLAB 代码如下:
```matlab
function [x] = gaussian_elimination(A, b)
% Input: A - coefficient matrix, b - constant matrix
% Output: x - solution vector
n = length(b);
% Forward elimination
for k = 1:n-1
[max_val, max_idx] = max(abs(A(k:n, k)));
max_idx = max_idx + k - 1;
if max_val == 0
error('Matrix is singular')
end
A([k, max_idx], :) = A([max_idx, k], :);
b([k, max_idx]) = b([max_idx, k]);
for i = k+1:n
factor = A(i, k) / A(k, k);
A(i, k:n) = A(i, k:n) - factor * A(k, k:n);
b(i) = b(i) - factor * b(k);
end
end
% Back substitution
x = zeros(n, 1);
x(n) = b(n) / A(n, n);
for i = n-1:-1:1
x(i) = (b(i) - A(i, i+1:n)*x(i+1:n)) / A(i, i);
end
end
```
LU 分解法的 MATLAB 代码如下:
```matlab
function [L, U] = lu_decomposition(A)
% Input: A - coefficient matrix
% Output: L, U - lower and upper triangular matrices
n = size(A, 1);
L = eye(n);
U = A;
for k = 1:n-1
if U(k, k) == 0
error('Matrix is singular')
end
L(k+1:n, k) = U(k+1:n, k) / U(k, k);
U(k+1:n, k:n) = U(k+1:n, k:n) - L(k+1:n, k) * U(k, k:n);
end
end
```
使用这些函数求解线性方程组的代码如下:
```matlab
% Example usage
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
b = [1; 2; 3];
[L, U] = lu_decomposition(A);
y = forward_substitution(L, b);
x = backward_substitution(U, y);
```
阅读全文