Tag: Jacobi

  • Matlab – Solusi Persamaan Linier dengan Metode Jacobi dan Gauss-Seidel

    Matlab – Solusi Persamaan Linier dengan Metode Jacobi dan Gauss-Seidel

    AhmadDahlan.Net– Mari kita asumsikan kasus Persamaan Linier sebagai berikut :

    a11x1+a12x2+...+a1nxn=b1
    a21x2+a22x2+...+a2nbn=b2
    .
    .
    . am1x1+am2x2+...+amnbn=bn

    Metode Jacobi dilakukan untuk persamaan linier dimana a11, a21, .. am1 tidak 0. Solusi dari masalah ini adalah :

    x1=1/a11(b1 - a12x2 - a13x3 - … a1nxn)
    x2=1/a22(b2 - a22x2 - a23x3 - … a2nxn)
    .
    .
    . xm=1/amm(bm - am2xm - am3xm - … amnxn)

    Solusi dari Jacobi Metode untuk masalah ini adalah :

    Metode Jacoby untuk persamaan Linier

    for i=1,2,..,n

    A. Metode Gauss-Seidel

    Matrik awal A, b dan perkiraan x, inpuut-nya

    A=[5 -2 3 0 6; -3 9 1 -2 7.4; 2 -1 -7 1 6.7; 4 3 -5 7 9; 2 3.5 6.1 -4 -8.1]
    
    A =
    5.0000 -2.0000 3.0000 0 6.0000 -3.0000 9.0000 1.0000 -2.0000 7.4000 2.0000 -1.0000 -7.0000 1.0000 6.7000 4.0000 3.0000 -5.0000 7.0000 9.0000 2.0000 3.5000 6.1000 -4.0000 -8.1000
    
    b=[-1 2 3 0.5 3.1]'
    
    b =
    -1.0000 2.0000 3.0000 0.5000 3.1000
    
    x=rand(5,1)
    
    x =
    0.5447 0.6473 0.5439 0.7210 0.5225
    
    n=size(x,1);
    normVal=Inf;
    % toleransi
    tol=1e-3; GaussItr=0;

    Script Solusi

    plotGauss=[];
    while normVal>tol 
        x_old=x; 
        for i=1:n 
            sigma=0; 
            for j=1:i-1 
                sigma=sigma+A(i,j)*x(j); 
            end 
            for j=i+1:n 
                sigma=sigma+A(i,j)*x_old(j); 
            end x(i)=(1/A(i,i))*(b(i)-sigma); 
        end 
        GaussItr=GaussItr+1; 
        normVal=norm(x_old-x); 
        plotGauss=[plotGauss;normVal];
    end
    fprintf('solusinya adalah : \n%f\n%f\n%f\n%f\n%f in %d iterations',x,GaussItr);

    B. Metode Jacobi

    plotJacobi=[];
    while normVal>tol 
        xold=x; 
        for i=1:n 
           sigma=0; 
           for j=1:n 
               if j~=i 
                 sigma=sigma+A(i,j)*x(j); 
               end 
           end 
           x(i)=(1/A(i,i))*(b(i)-sigma); 
         end 
         JacobItr=JacobItr+1; 
         normVal=norm(xold-x); 
         plotJacobi=[plotJacobi;normVal];
    end
    
    fprintf('Solusi : \n%f\n%f\n%f\n%f\n%f in %d iterations',x,JacobItr);

    C. Perbandingan Hasil Metode Gauss Seidel Vs Jacobi

    figure
    hold on
    plot(1:5:GaussItr,plotGauss(1:5:GaussItr),'LineWidth',2)
    plot(1:5:JacobItr,plotJacobi(1:5:JacobItr),'LineWidth',2)
    text(GaussItr,0.2,'\downarrow')
    text(GaussItr,0.3,'Gauss Seidel')
    text(JacobItr,0.3,'\downarrow')
    text(JacobItr,0.4,'Jacobi')
    legend('Gauss Seidel ','Jacobi ')
    ylabel('Error Value')
    xlabel('Number of iterations')
    title('Gauss Seidel Vs Jacobi')
    hold off