How to simulate travelling wave with finite difference?

This may sounds a stupid question. Anyway, I have coded (in Matlab) finite difference method to compute numerical solution of wave equation. You can find the problem here:

and the solution, which I am able to compute is here

For me, this problem simulates a string attached wall to wall, and we give force at the left wall, so we now have a wave.

My question is, how do I simulates traveling wave, like here

or what if the wave doesn't go back after hitting the right endpoint(it just gone, like in shore).. What would I need to change to achieve it? is it the boundary condition?

• You would have to give the initial wave some speed, for some short time you would like your solution to look like $u(x,t)=f(x-ct)=u(x-ct,0)$ which leads to the initial velocity condition $u_t(x,0)+cu_x(x,0)=0$. – Dr. Lutz Lehmann May 20 '18 at 11:25
Suppose your wave equation reads $$u_{tt}=a^2u_{xx}.$$ Let $$u_j^n\approx u(t_n,x_j).$$ Let $k$ be your time step, and $h$ be your spatial step. Let $$0=x_0<x_1<\cdots<x_N=1,$$ with $x_j=jh$. Your finite difference scheme could be $$\frac{u_j^{n+1}-2u_j^n+u_j^{n-1}}{k^2}=a^2\frac{u_{j+1}^n-2u_j^n+u_{j-1}^n}{h^2},\quad j=1,2,\cdots,N-1.$$
If you expect that the wave could propagate beyond $x=0$ and $x=1$, i.e., $u$ is defined for $x<0$ and $x>1$. Then you are assuming that $u_{tt}=a^2u_{xx}$, and hence the above discretized scheme, applies at $x=0$ and $x=1$ as well.
Take $x=1$ for instance. Since the scheme holds at $x=1$, you must put $j=N$, i.e., $$\frac{u_N^{n+1}-2u_N^n+u_N^{n-1}}{k^2}=a^2\frac{u_{N+1}^n-2u_N^n+u_{N-1}^n}{h^2}.$$ In this last scheme, everything is fine except the "ghost" $u_{N+1}^n$ term. Nevertheless, it suffices to approximate $u_{N+1}^n$ by using $u_N^n$, $u_{N-1}^n$, etc. For example, $$u_{N+1}^n=2u_N^n-u_{N-1}^n,$$ which is second-order accurate, because \begin{align} u(t_n,x_{N+1})&=u(t_n,x_N+h)\\ &=2u(t_n,x_N)-u(t_n,x_N-h)+O(h^2)\\ &=2u(t_n,x_N)-u(t_n,x_{N-1})+O(h^2). \end{align} You may check this by Taylor expansion. You could make use of $u_{N-2}^n$, $u_{N-3}^n$, ..., as well if you wish to get a higher order of accuracy.
Similar trick also applies to the other "ghost" $u_{-1}^n$.