c=2; deltax=0.01; deltat=deltax/5; Nx=1/deltax+1; % total points along x x=0:deltax:1; T=1.5; % total time Nt=round(T/deltat+1); % total points along t
U=zeros(Nt,Nx); U(1,:)=3*x.*(x<=1/3)+3/2*(1-x).*(x>=1/3); % the first IC U(2,:)=U(1,:); % the second IC U(:,1)=0; U(:,end)=0; % BCs
r=c^2*(deltat/deltax)^2; for n=2:Nt U(n+1,2:end-1)=-U(n-1,2:end-1)+r*U(n,1:end-2)+(2-2*r)*U(n,2:end-1)+r*U(n,3:end); % 离散格式 end
读者需要注意或者学习的是最后for循环里面的一句长指令,这句指令将看似比较麻烦的离散方程
高效地用代码表述,相信我,这是非常有用的Matlab高效编程技巧!
这是生成动图的代码:
figure fori=1:Nt plot(x,U(i,:),'LineWidth',1.4) xlabel('x') ylabel('u') ylim([-1.5,1.5]) set(gca,'PlotBoxAspectRatio',[10.41],'FontSize',15) title(['t=',num2str((i-1)*deltat)]) drawnow end