MATLAB Examples

Wave Equation Using Command-Line Functions

This example shows how to solve the wave equation using command-line functions. It solves the equation with boundary conditions u = 0 at the left and right sides, and $\partial u/\partial n = 0$ at the top and bottom. The initial conditions are

$$ u(x,y,0) = \arctan\left (\cos\left (\frac{\pi}{2} x\right )\right )$$


$$\frac{\partial u}{\partial t} = 3\sin(\pi x)\exp\left (\sin\left
(\frac\pi 2 y\right )\right ) \hbox{ at }t = 0.$$

Calculate the solution every 0.05 seconds for five seconds.

The geometry is described in the file squareg.m.

First, create the geometry.

model = createpde();

View the geometry

axis equal

Set the boundary conditions to u = 0 on the left and right boundaries (edges 2 and 4). The default boundary conditions are appropriate for edges 1 and 3, so you do not need to set them.


Set the initial conditions.

u0 = @(locations)atan(cos(pi/2*locations.x));
ut0 = @(locations)3*sin(pi*locations.x).*exp(sin(pi/2*locations.y));

Create the model coefficients. The equation is

$$m\frac{\partial^2 u}{\partial t^2}-\nabla\cdot(c\nabla u) = f,$$

where $m = 1$, $c = 1$, and $f = 0$.

m = 1;
c = 1;
f = 0;

Set the solution times.

n = 31; % number of frames in eventual animation
tlist = linspace(0,5,n); % list of times

You are now ready to solve the wave equation. Create a mesh and call the solver.

results = solvepde(model,tlist);

Animate the solution.

u = results.NodalSolution;

umax = max(max(u));
umin = min(min(u));

M = moviein(n);
for i=1:n,
    axis([-1 1 -1 1 umin umax]);
    caxis([umin umax]);
    M(:,i) = getframe;

You can review the movie by executing movie(M,10). There is a complete solution of this problem, including animation, in docid:pde_examples.example-ex08381761. If you have lots of memory, you can try increasing n, the number of frames in the movie.