用gauss消去法求解线性方程组的matlab代码
时间: 2023-05-29 10:04:17 浏览: 72
function [x] = gauss(A,b)
% Gauss elimination method to solve linear equations
% A: coefficient matrix
% b: constant term vector
% x: solution vector
% check if the coefficient matrix is square
[m,n] = size(A);
if m ~= n
error('The coefficient matrix must be square!');
end
% check if the size of the constant term vector matches the coefficient matrix
if length(b) ~= n
error('The size of the constant term vector must match the coefficient matrix!');
end
% augmented matrix
aug = [A,b];
% forward elimination
for k = 1:n-1
for i = k+1:n
factor = aug(i,k) / aug(k,k);
aug(i,k:end) = aug(i,k:end) - factor * aug(k,k:end);
end
end
% back substitution
x = zeros(n,1);
x(n) = aug(n,n+1) / aug(n,n);
for i = n-1:-1:1
x(i) = (aug(i,n+1) - aug(i,i+1:n) * x(i+1:n)) / aug(i,i);
end
end