Solution of Possion2D equation with method of Gauss-Seidel iteration.

%set parameter
N1 = 31; 
N2 = 41;
L1 = 1000; 
L2 = 1500; 
rp = 1.5;%relaxation parameter
deltax = L1 / (N1 - 1)
deltay = L2 / (N2 - 1)

figure(1)
title('Solution of Gauss-Seidel iteration');    
subplot(1,2,1)
output_interval = 10
%initialize grids
[x,y] = meshgrid(0:L2/(N2-1):L2,0:L1/(N1-1):L1);%meshgrid:x and y are interchangeable
u = zeros(N1, N2);
residual_matrix = zeros(N1,N2)
g = size(u)
%set boundary condition
u(1, :) = 0; % underdown boundary
u(N1, :) = 0; % up boundary
u(:, 1) = 0; % left boundary
u(:, N2) = 0; % right boundary

%interation solution
%margin of error
tolerance = 1e-6;
%max mumber
maxIter = 100; 
iter = 0;
while (iter < maxIter)
    iter = iter + 1;
    u_old = u;
    for i = 2:N1-1
        for j = 2:N2-1
            %Jacobi iteration:new values are assigned after finishing a one
            %circle of iterations
            u(i, j) = u_old(i, j)+rp * ( (1-(u_old(i-1, j)./(deltax.^2) + u_old(i+1, j)./(deltax.^2) + u_old(i, j-1)./(deltay.^2) + u_old(i, j+1)./(deltay.^2)+ u_old(i,j).*((-2)./(deltax.^2)+(-2)./(deltay.^2))) )/ ((-2)./(deltax.^2)+(-2)./(deltay.^2)));
            residual_matrix(i,j) = (1-(u_old(i-1, j)./(deltax.^2) + u_old(i+1, j)./(deltax.^2) + u_old(i, j-1)./(deltay.^2) + u_old(i, j+1)./(deltay.^2)+ u_old(i,j).*((-2)./(deltax.^2)+(-2)./(deltay.^2))) )
        end
    end
    %compare residual with tolerance
    residual = max(abs(residual_matrix), [], 'all')
    if (residual < tolerance)
        break;
    end
    %iter is a multiple of 10
    if mod(iter, output_interval) == 0
        mesh(y, x, residual_matrix);
        xlabel('x');
        ylabel('y');
        zlabel('residual_matrix');
        drawnow;
    end
end

%visualize solution of possion2D equation
% figure(2)
subplot(1,2,2)
mesh(y, x, u);
xlabel('x');
ylabel('y');
zlabel('u');
colorbar

 

Solution of Possion2D equation with method of Gauss-Seidel iteration._第1张图片

Enlarge :Solution of Possion2D equation with method of Gauss-Seidel iteration._第2张图片

 

 Solution of Possion2D equation with method of Gauss-Seidel iteration._第3张图片

 

 

你可能感兴趣的:(Gauss-Seidel,iteration,Possion2D,equ)