% p2.m: the pseudo-spectral method for solving the NLS equation
% iu_t+u_{xx}+2|u|^2u=0.

  L=80; N=256; dt=0.02; tmax=20; nmax=round(tmax/dt);
  dx=L/N; x=[-L/2:dx:L/2-dx]'; k=[0:N/2-1 -N/2:-1]'*2*pi/L; k2=k.^2;
  u=1.2*sech(1.2*(x+20)).*exp(i*x)+0.8*sech(0.8*x);
  udata=u; tdata=0;
  for nn=1:nmax                               % integration begins
    du1=i*(ifft(-k2.*fft(u))+2*u.*u.*conj(u));  v=u+0.5*du1*dt;
    du2=i*(ifft(-k2.*fft(v))+2*v.*v.*conj(v));  v=u+0.5*du2*dt;
    du3=i*(ifft(-k2.*fft(v))+2*v.*v.*conj(v));  v=u+    du3*dt;
    du4=i*(ifft(-k2.*fft(v))+2*v.*v.*conj(v));
    u=u+(du1+2*du2+2*du3+du4)*dt/6;
    if mod(nn,round(nmax/25)) == 0
       udata=[udata u]; tdata=[tdata nn*dt];
    end
  end                                         % integration ends
  waterfall(x, tdata, abs(udata'));           % solution plotting
  colormap([0 0 0]); view(10, 60)
  text(-2,  -6, 'x', 'fontsize', 15)
  text(50, 5, 't', 'fontsize', 15)
  zlabel('|u|', 'fontsize', 15)
  axis([-L/2 L/2 0 tmax 0 2]); grid off
  set(gca, 'xtick', [-40 -20 0 20 40])
  set(gca, 'ytick', [0 10 20])
  set(gca, 'ztick', [0 1 2])