MATLAB中泊松方程的逼近解

时间:2019-05-05 13:47:42

标签: matlab math vector matrix-multiplication differential-equations

我正在尝试在Matlab中使用五点有限差分法来解决边值问题:

enter image description here

我找到了一个解决方案:

enter image description here

使用以下代码

function Poisson_diko_m(n,niter)

% Solves the Poisson equation
% using the five-point finite-difference method

b=zeros(niter,1);

for iter=1:niter
h=1/n;n2=(n-1)^2;
%fprintf('n =%2.0f\n',n)

% Compute grid
x=zeros(n+1);y=zeros(n+1);
x=h*(0:n);y=h*(0:n);   

% matrix of grid values
u=zeros(n+1,n+1);

% Boundary conditions
u(1,:)=0;
u(n+1,:)=0;
u(:,1)=0;
u(:,n+1)=0;

%Matrix A and identity matrix
A=zeros(n-1,n-1);      
A=sparse((-2/h^2)*diag(ones(n-1,1))+(1/h^2)*diag(ones(n-2,1),1)+(1/h^2)*diag(ones(n-2,1),-1));   
%Full matrix
  AA=sparse(kron(A,eye(n-1))+kron(eye(n-1),A));

%right hand side
%for i=1:n-1
%for j=1:n-1
%ij=(i-1)*(n-1)+j;
%G(ij,1)=fr1(x(i+1),y(j+1));  
%end 
%end
G=reshape(fr1(x(2:n),y(2:n)),(n-1)^2,1);

% Solution of global system      
 C=AA\G;
 % Recover coefficients
  u(2:n,2:n)=(reshape(C,n-1,n-1))';
 %disp('______________________________________________________________________')
 %fprintf('   t           x               u           exact       error')
 %fprintf('\n')
 %disp('______________________________________________________________________')

 E=f1(x,y)';
%for i=1:n+1
%for j=1:n+1
%ij=(i-1)*(n-1)+j;
%E(i,j)=f1(x(i),y(j));  
%end 
%end 

  b(iter,1)=max(max(abs(E-u)));
  if iter==1
      rate=0;
  else
      rate=log(b(iter-1,1)/b(iter,1))/log(2);
  end
     fprintf('n=  %6.0f   Maximum error = %12.3e   Rate =     %12.4f\n',n,b(iter,1),rate);
    disp('______________________________________________________________________')
     n=2*n;
end
%for i=2:niter
%    rate(i)=log(b(i-1)/b(i))/log(2);
%end

%rate
A=(E-u)';

size(A);
x=0:h:1;
y=0:h:1;
[j nn]=size(x);
[l mm]=size(y);
z=reshape(A,mm,nn);
[X,Y]=meshgrid(x,y);
surf(X,Y,z);
zlim([1.e-8 1.e-7]);
ylabel('y'),xlabel('x'),zlabel('Error')
colormap(winter)

f = findobj('Type','surface');
set(f,'FaceLighting','phong');

material shiny
shading interp
light


function f=f1(x,y)
f=x.*(1-y').*cos(pi/2*x).*sin(pi/2*y);


function fr=fr1(x,y)
fr=(-1)*pi*(1-y').*sin(pi/2*x)-pi*x.*cos(pi/2*x).*cos(pi/2*y)-pi^2/2*x.*(1-y').*cos(pi/2*x).*sin(pi/2*y);

我调用了函数

Poisson_diko_m(2^3,8)

因为我想要近似为h = 1/2 ^ l,l = 3,...,10

但是结果似乎是错误的,因为我期望图形的倒置杯和误差会小得多,但是我得到了以下结果:

enter image description here

enter image description here

我猜错了一定是因为我是如何在Matlab代码的最底部而不是其余代码中实现这两个公式的。也许乘法维度是错误的,但我不确定。我尝试了一些虚拟的x和y来查看结果,但是它们看起来很正常。我不知道错误在哪里。任何帮助表示赞赏。

0 个答案:

没有答案