% p4.m: the 4th-order integrating-factor method for solving the NLS
% equation:  iu_t+u_{xx}+2|u|^2u=0.

  L=4*pi; N=128; dt=0.01; tmax=2; 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; E=exp(i*k.^2*dt/2); E2 = E.*E;
  u=sin(x).^2; udata=u; tdata=0;
  for nn = 1:nmax                       % integration begins
    v=fft(u);                  dv1=2*i*    fft(u.*u.*conj(u));
    w=ifft((v+dv1*dt/2)./E );  dv2=2*i*E.* fft(w.*w.*conj(w));
    w=ifft((v+dv2*dt/2)./E );  dv3=2*i*E.* fft(w.*w.*conj(w));
    w=ifft((v+dv3*dt  )./E2);  dv4=2*i*E2.*fft(w.*w.*conj(w));
    v=v+(dv1+2*dv2+2*dv3+dv4)*dt/6;  u=ifft(v./E2);
    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(5, 60)
  xlabel('x', 'fontsize', 15)
  ylabel('t', 'fontsize', 15)
  zlabel('|u|', 'fontsize', 15)
  axis([-L/2 L/2 0 tmax 0 2]); grid off