用matlab编写一个可以选择使用LU分解或Cholesky分解求解任意线性方程组的程序,且不使用lu函数和chol函数
时间: 2024-05-21 18:10:17 浏览: 98
以下是一个可以选择使用LU分解或Cholesky分解求解任意线性方程组的MATLAB程序:
function x = solve_linear_equations(A, b, method)
% A: 系数矩阵
% b: 常数向量
% method: 'LU' 或 'Cholesky'
n = size(A, 1);
if strcmpi(method, 'LU')
% LU分解
[L, U] = LU_decomposition(A);
% 前向替换
y = forward_substitution(L, b);
% 后向替换
x = backward_substitution(U, y);
elseif strcmpi(method, 'Cholesky')
% Cholesky分解
L = Cholesky_decomposition(A);
% 前向替换
y = forward_substitution(L', b);
% 后向替换
x = backward_substitution(L, y);
else
error('未知的方法');
end
function [L, U] = LU_decomposition(A)
% LU分解
n = size(A, 1);
L = eye(n);
U = A;
for k = 1:n-1
% 部分主元消去
[~, i] = max(abs(U(k:n, k)));
i = i + k - 1;
if U(i, k) == 0
error('矩阵不可逆');
end
if i ~= k
U([i, k], k:n) = U([k, i], k:n);
L([i, k], 1:k-1) = L([k, i], 1:k-1);
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
function L = Cholesky_decomposition(A)
% Cholesky分解
n = size(A, 1);
L = zeros(n);
for k = 1:n
% 求L(k, k)
L(k, k) = sqrt(A(k, k) - sum(L(k, 1:k-1).^2));
if L(k, k) == 0
error('矩阵不可逆');
end
% 求L(i, k)
for i = k+1:n
L(i, k) = (A(i, k) - sum(L(i, 1:k-1).*L(k, 1:k-1))) / L(k, k);
end
end
function y = forward_substitution(L, b)
% 前向替换
n = size(L, 1);
y = zeros(n, 1);
for i = 1:n
y(i) = (b(i) - L(i, 1:i-1)*y(1:i-1)) / L(i, i);
end
function x = backward_substitution(U, y)
% 后向替换
n = size(U, 1);
x = zeros(n, 1);
for i = n:-1:1
x(i) = (y(i) - U(i, i+1:n)*x(i+1:n)) / U(i, i);
end
使用示例:
A = [4, -1, 1; -1, 4.25, 2.75; 1, 2.75, 3.5];
b = [1; 2; 3];
x1 = solve_linear_equations(A, b, 'LU');
x2 = solve_linear_equations(A, b, 'Cholesky');
阅读全文