Solution of Possion2D equation with direct method.

%set parameter
N1 = 41; 
N2 = 31;
L1 = 1500; 
L2 = 1000; 
rp = 1.0;%relaxation parameter
deltax = L1 / (N1 - 1);
deltay = L2 / (N2 - 1);
[x,y] = meshgrid(0:L2/(N2-1):L2,0:L1/(N1-1):L1);%meshgrid:x and y are interchangeable
coe = zeros(N1*N2, N1*N2);
%coefficients of boundary
%up and down
for i = 1:N1
    j = 1
    k = (i-1)*N2 + j;
    coe(k, k) = 1;
    j = N2
    k = (i-1)*N2 + j;
    coe(k, k) = 1;    
end
%left and right
for j = 1:N2
    i = 1
    k = (i-1)*N2 + j;
    coe(k, k) = 1;
    i = N1
    k = (i-1)*N2 + j;
    coe(k, k) = 1;
end
%coefficients of interval points
for i = 2:N1-1
    for j = 2:N2-1
        k = (i-1)*N2 + j; % k表示网格点 (i,j) 对应的未知量索引
        coe(k, k) = -2./(deltax.^2)-2./(deltay.^2); % 中心点系数
        coe(k, k-1) = 1./(deltax.^2); % 左边点系数
        coe(k, k+1) = 1./(deltax.^2); % 右边点系数
        coe(k, k-N2) = 1./(deltay.^2); % 上边点系数
        coe(k, k+N2) = 1./(deltay.^2); % 下边点系数
    end
end
%set right hand side martix
%right value equal to 1 except boundary points
b = ones(N1*N2, 1);
%up and down
for i1 = 1:N1
    j1 = 1
    k = (i1-1)*N2 + j1;
    b(k, 1) = 0;
    j1 = N2
    k = (i1-1)*N2 + j1;
    b(k, 1) = 0;
end
%left and right
for j1 = 1:N2
    i1 = 1
    k = (i1-1)*N2 + j1;
    b(k, 1) = 0;
    i1 = N1
    k = (i1-1)*N2 + j1;
    b(k, 1) = 0;
end
%direct method:right martix is divided by coe martix on the left
u = coe \ b
%transform vector to grids 
U = zeros(N1, N2);
U = reshape(u, N2, N1);
%this line is necessary:because of tops and bottoms' program are not consistent 
[X,Y] = meshgrid(0:L1/(N1-1):L1,0:L2/(N2-1):L2)
%visualize solution of possion2D equation
mesh(X,Y, U);
xlabel('y');
ylabel('x');
zlabel('Gravitational potential');
title('Direct solution of Possion2D equation')

Solution of Possion2D equation with direct method._第1张图片

 

你可能感兴趣的:(Possion2D,equ,direct,method,numerical,sol)