An archived instance of discourse for discussion in undergraduate PDE.

Animation of diffustion

Mark

How can I use Mathematica to animate a heat diffusion problem - both in the Mathematica notebook and in a webpage, like here on Discourse?

As a specific example, consider the heat problem
$$
\begin{array}{ll}
u_t = u_{xx} & u(x,0) = 2x^2-x \\
u(0,t) = 0 & u(1,t) = e^{-t}.
\end{array}
$$





So, I guess the initial configuration here will be a parabola ($2x^2-x$) through the origin and $(1,1)$. The left and endpoint will remain fixed while the right hand endpoint will decrease with time. Heat will diffuse out of the bar and approach a zero steady state, though the right hand end point will never actually hit zero. How can we visualize this numerically?

Audrey

As described in Mark's fabulous NDSolve for 1D diffusion notebook on our class website, we can use Mathematica's NDSolve command to generate a numerical solution and the Plot command to generate graphs of the solution at various points in time. From that point, there are a couple of paths to animate the process. The notebook on our webpage shows how to use the Animate command. If you want an animation in a webpage, you can generate a Table of images, Export that to GIF, and then embed the result in a webpage as you would any image. Let's try.

Again, as described in the NDSolve for 1D diffusion notebook, we can generate a numerical solution to the above heat problem as follows

Clear[u];
sol = NDSolve[{
  D[u[x, t], t] == D[u[x, t], x, x],
  u[x, 0] == 2 x^2 - x, u[0, t] == 0, 
  u[1, t] == Exp[-t]}, u[x, t],
  {x, 0, 1}, {t, 0, 2}];
u[x_, t_] = u[x, t] /. First[sol]

Now, though the result looks strange, we can use the function u[x,t] pretty much like any other. In particular, we can plot it as a function of $x$ at any fixed point in time. Here's what the initial condition looks like.

Plot[u[x, 0], {x, 0, 1}]

And, a split second later.

Plot[u[x, 0.1], {x, 0, 1}]

As described in the notebook, we can use the Animate command to generate an animation in the notebook.

Animate[Plot[u[x, t], {x, 0, 1},
  PlotRange -> {-0.3, 1}], {t, 0, 2}]
(* Output supressed *)

To include such an animation here (or in any webpage), we need to generate a Table of images, Export that to GIF, and then embed the result. Here's how to generate the sequence of images.

pics = Table[Plot[u[x, t], {x, 0, 1},
  PlotRange -> {-0.3, 1}], {t, 0, 2, 0.02}];

Note that we've stored the result in the variable pics and suppressed the (huge) output with a semi-colon. Other than that, the command looks remarkably like the Animate command, though, it does include a stepSize of 0.02. Now, we generate an animated GIF as follows:

Export["anim.gif", pics];

After that, there should be a new GIF file on your hard drive, probably in your home directory. In a web browser, it looks like so: