高斯法
Guass.m文件:
function x = Guass(A,b)
n = length(b);
for j=1:n
for i=j+1:n
if A(j,j)~=0
M(i,j)=A(i,j)/A(j,j);
for k=j:n
A(i,k)=A(i,k)-M(i,j)*A(j,k);
end
b(i)=b(i)-M(i,j)*b(j);
else
error('无法用高斯法求解')
end
end
end
x(n)=b(n)/A(n,n);
i=n-1;
while i>0
s=0;
for j=i+1:n
s=A(i,j)*x(j)+s;
end
x(i)=(b(i)-s)/A(i,i);
i=i-1;
end
控制台输入:
矩阵存在csv文件中,用excel写矩阵保存成csv文件,matlab读取csv文件。
>> filename =’E:\矩阵\A.csv’;
A = csvread(filename,0,0,[0,0,8,8]);
b = csvread(filename,0,9);
>> Guass(A,b)
列主元消去法
ColGauss.m文件:
function x = ColGuass(A,b)
n = length(b);
for j=1:n
for i=j+1:n
for k=i:n
if abs(A(k,j))>abs(A(j,j))
for k1=j:n
a1=A(j,k1);
a2=A(k,k1);
A(j,k1)=a2;
A(k,k1)=a1;
end
t=b(k);
b(k)=b(j);
b(j)=t;
end
end
if A(j,j)~=0
M(i,j)=A(i,j)/A(j,j);
for k=j:n
A(i,k)=A(i,k)-M(i,j)*A(j,k);
end
b(i)=b(i)-M(i,j)*b(j);
else
error('无法用列主元消去法求解')
end
end
end
x(n)=b(n)/A(n,n);
i=n-1;
while i>0
s=0;
for j=i+1:n
s=A(i,j)*x(j)+s;
end
x(i)=(b(i)-s)/A(i,i);
i=i-1;
end
控制台输入:
>> filename =’E:\矩阵\A.csv’;
A = csvread(filename,0,0,[0,0,8,8]);
b = csvread(filename,0,9);
>>ColGuass(A,b)
LU分解
LU.m文件:
function [L,U]=LU(a,n)
L = zeros(n,n);
for i = 1:n; L(i,i) = 1; end
for j = 1 : n-1
if abs(a(j,j))<eps
error('errord');
end
for i = j+1 : n
mult = a(i,j)/a(j,j);
L(i,j) = mult;
for k = j:n
a(i,k) = a(i,k) - mult*a(j,k);
end
end
end
U = a;
控制台输入:
LU分解结果:
>> filename ='E:\矩阵\A.csv';
A = csvread(filename,0,0,[0,0,8,8]);
b = csvread(filename,0,9);
[L,U] = LU(A,9);
列主元的LU分解
控制台输入:
调用matlab内置函数lu():
>> [L,U,P] = lu(A);
逆矩阵、行列式
控制台输入:
>> inv_A = inv(U)*inv(L);
>> det_A = det(U)*det(L);