% Compute and plot the results of a fd code on a simple grid J = 4; N = 8; T = 0.2; x = linspace(0,1,J+1); t = linspace(0,T,N+1); u = zeros(j+1,n+1); h=zeros(J+1,N+1); % plot the grid figure(1),clf axis off hold on for j=1:J+1 line(repmat(x(j),1,N+1),t,'color','k') end for n=1:N+1 line(x,repmat(t(n),1,J+1),'color','k') end for j=1:J+1 line(x(j),t(1),'marker','o','markerfacecolor','r','markeredgecolor','k','markersize',5) end for n=2:N+1 line(x(1),t(n),'marker','o','markerfacecolor','r','markeredgecolor','k','markersize',5) line(x(end),t(n),'marker','o','markerfacecolor','r','markeredgecolor','k','markersize',5) end for j=2:J for n=2:N+1 line(x(j),t(n),'marker','o','markerfacecolor','b','markeredgecolor','k','markersize',5) end end drawnow pause pos = get(gca,'position'); for j=1:J+1 for n=1:N+1 h(j,n) = annotation('textbox',... [pos(1)+(x(j)-0.05)*pos(3),pos(2)+(t(n)/T-0.075)*pos(4),... 0.1*pos(3),0.06*pos(4)]); set(h(j,n),'backgroundcolor',0.8*[1 1 1],... 'horizontalalignment','center','verticalalignment','middle') set(h(j,n),'string','') end end drawnow pause % Now perform an explicit finite difference computation. % Set the boundary values nu = T*J^2/N; for j=1:J+1 u(j,1) = x(j)^2; set(h(j,1),'string',sprintf('%5.3f',u(j,1))) end for n = 2:N+1 u(1,n) = 0; u(J+1,n) = 1; set(h(1,n),'string',sprintf('%5.3f',u(1,n))) set(h(J+1,n),'string',sprintf('%5.3f',u(J+1,n))) end drawnow pause % Loop through time and across the grid for n=2:N+1 for j=2:J set(h(j,n),'backgroundcolor','w') set(h(j-1,n-1),'backgroundcolor','w') set(h(j,n-1),'backgroundcolor','w') set(h(j+1,n-1),'backgroundcolor','w') pause(0.5) u(j,n) = (1-2*nu)*u(j,n-1)+nu*(u(j-1,n-1)+u(j+1,n-1)); set(h(j,n),'string',sprintf('%5.3f',u(j,n))) pause(0.5) set(h(j,n),'backgroundcolor',0.8*[1 1 1]) set(h(j-1,n-1),'backgroundcolor',0.8*[1 1 1]) set(h(j,n-1),'backgroundcolor',0.8*[1 1 1]) set(h(j+1,n-1),'backgroundcolor',0.8*[1 1 1]) end % impose a zero-derivative condition at the RHS set(h(J+1,n),'backgroundcolor','w') set(h(J,n-1),'backgroundcolor','w') set(h(J+1,n-1),'backgroundcolor','w') pause(0.5) u(J+1,n) = (1-nu)*u(J+1,n-1)+nu*u(J,n-1); set(h(J+1,n),'string',sprintf('%5.3f',u(J+1,n))) pause(0.5) set(h(J+1,n),'backgroundcolor',0.8*[1 1 1]) set(h(J,n-1),'backgroundcolor',0.8*[1 1 1]) set(h(J+1,n-1),'backgroundcolor',0.8*[1 1 1]) end