np = 1000;
L = 30;
a2 = 4;
x = linspace(0, 1, np);
nmax = 500;
U0 = 1;

h = figure;
axis tight manual % this ensures that getframe() returns a consistent size
filename = 'waves3.gif';

nt = 1000;
tmin = 0;  % 
tmax = 30;   % 
tt = linspace(tmin, tmax, nt);

for t = tt
    u = 2/L*elstring(x, t, sqrt(a2), L, nmax);
    plot(x, u);
    xlabel('x/L')        % x-axis label
    ylabel('U / U_0') % y-axis label
    teff = sqrt(a2)*t/L;
    title(['a t/L = ',num2str(teff,'%10.6f\n')])
    ylim([-1.05*U0 1.05*U0]);
    drawnow();
    pause(0.1);
    
    % Capture the plot as an image 
    frame = getframe(h); 
    im = frame2im(frame); 
    [imind, cm] = rgb2ind(im, 256); 
    
    % Write to the GIF File 
    if t == tt(1) 
        imwrite(imind, cm, filename, 'gif', 'Loopcount', inf); 
    else 
        imwrite(imind, cm, filename, 'gif', 'WriteMode', 'append'); 
    end 
end

function u = elstring(x, t, a, L, nmax)
    np = length(x);
    u = zeros(1, np);
    for m = 1:nmax
        bm = exp(-(pi*m/60)^2)*sqrt(pi)*sin(m*pi/2);
        u = u + bm*sin(pi*m*x)*cos(m*a*pi*t/L);
    end
end
