Gauss 列主元消去法的matlab代码
时间: 2023-06-04 14:04:00 浏览: 676
以下是Gauss列主元消去法的Matlab代码:
function [x, L, U] = gauss_pivot(A, b)
% GAUSS_PIVOT Performs Gauss elimination with partial pivoting
% on augmented matrix A|b.
% Returns the solution vector x, the lower triangular matrix L,
% and the upper triangular matrix U.
%
% Usage: [x, L, U] = gauss_pivot(A, b)
%
% Note: This code does not check for singularity or near-singularity.
%
% Example:
% A = [1 2 -3; 4 5 6; 7 8 9];
% b = [5; 7; 9];
% [x, L, U] = gauss_pivot(A, b);
% Get size of augmented matrix
[n,~] = size(A);
% Initialize L and U
L = eye(n);
U = A;
% Perform Gauss elimination with partial pivoting
for k = 1:n-1
% Find row r in columns k through n of U with largest magnitude
[~,r] = max(abs(U(k:n,k)));
r = r + k - 1;
% Swap rows k and r of U and b
temp = U(k,:);
U(k,:) = U(r,:);
U(r,:) = temp;
temp = b(k);
b(k) = b(r);
b(r) = temp;
% Swap rows k and r of L
if k > 1
temp = L(k,1:k-1);
L(k,1:k-1) = L(r,1:k-1);
L(r,1:k-1) = temp;
end
% Perform elimination
for i = k+1:n
L(i,k) = U(i,k)/U(k,k);
for j = k:n
U(i,j) = U(i,j) - L(i,k)*U(k,j);
end
b(i) = b(i) - L(i,k)*b(k);
end
end
% Solve for x using backward substitution
x = zeros(n,1);
x(n) = b(n)/U(n,n);
for i = n-1:-1:1
x(i) = (b(i) - U(i,i+1:n)*x(i+1:n))/U(i,i);
end
end
阅读全文