1. 程式人生 > >列主元素法,matlab實現

列主元素法,matlab實現

clc;
clear;
A(:,:)=input('請輸入係數矩陣:\n');
A
n = length(A);
n
B(1,:)=input('請輸入B向量:\n');
B
for i = 1:n-1
    tmp = A(i,i);
    pos = i;
    for j = i+1:n  %尋找最大列;
        if A(j,i) > tmp
            tmp = A(j,i)
            pos = j
        end
    end
   for j = 1:n %交換第i行與第pos行;
       m = A(i,j);
       A(i,j) = A(pos,j);
       A(pos,j) = m;
   end
 
    m = B(i);
    B(i) = B(pos);
    B(pos) = m;
    for j = i+1:n
        tmp = A(j,i)/A(i,i);
        for k = i:n
          A(j,k) = A(j,k)-tmp * A(i,k);
        end
        B(j) = B(j) - B(i)*tmp;
    end
end
A
B
for i = n:-1:1
 tmp = n;
 while tmp > i
     B(i) = B(i)-A(i,tmp)*X(tmp);
     tmp = tmp - 1;
 end
 X(i) = B(i)/A(i,i);
end
X