MATLAB code: Fourier spectral method for 2D Cahn-Hilliard equation

Date:

%The space is discretized with Fourier spectral method and the time is discretized with first-order backward Euler method.

clear all;

N = 200; L=1; x=linspace(0,L,N+1); y=x; v = 0.01*(rand(N,N)-0.5);

dt = 0.001; T=3;

k=2pi/L[0:N/2 -N/2+1:-1];

p=k;

k2=k.^2;

p2=p.^2;

[kk2, pp2]=meshgrid(k2,p2);

kp=kk2+pp2;

kp2=kp.^2;

nplots = round(T/dt); clf; hold on; t=0;

eps2=0.01^2;

for iter = 1:nplots

u=real(v);

f=u.^3-3*u;

v_hat = fft2(u/dt)-kp.*fft2(f); %Converts to fourier space

v_hat = v_hat./(1.0/dt+2.0kp+eps2kp2); %Backwards Euler timestepping

v = ifft2(v_hat); %Converts back to real Space

t=t+dt;

if (mod(iter,10)==0)

clf

surf(x(2:end),y(2:end),real(v'));

shading interp

axis image

view(0,90)   

pause(0.01)

end

end