% Plot of Fourier approximation of a square wave as a function of the
% number of included Fourier components in the sum 

clear; close all
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
vid = VideoWriter('squareWave_v_n.mp4','MPEG-4');
vid.FrameRate = 30;    % Default 30
vid.Quality = 100;    % Default 75
open(vid);
set(gcf,'Color','k'); % Black background 

pos1 = [0 0 1 1]; % Use up all of the screen 
nmax = 81; % n-value of maximum Fourier component. Must be an odd integer 
frmsPerComp = 15; % Number of frames for growing in a given n

% Colour palette from red to violet through the colours of the rainbow 
rgb = customcolormap([0 0.17 0.33 0.5 0.67 0.83 1],...
    {'#ff0000', '#ffa500', '#ffff00', '#00ff00',...
    '#00ffff', '#0000ff', '#7f00ff'},((nmax+1)/2)*frmsPerComp);
rgb = flip(rgb);

thc = 0:pi/1440:6*pi; % x-axis: time or distance 
sum = 0.0*thc; % Initialize Fourier sum to zero 
colindex = 0; 
subplot('position',pos1);
for n = 1:2:nmax % Fourier components, odd values only 
    y = (1/n)*sin(n*thc); % nth Fourier component 
    % Add each component slowly by ramping its contribution up from 0 to 
    % its proper value using "ampl" 
    for ampl = 1/frmsPerComp:1/frmsPerComp:1         
        colindex = colindex+1;
        rgbcol = rgb(colindex,:); % Assign new colour to each plot
        ynow = sum + ampl*y;
        plot(thc, ynow, 'color', rgbcol, 'LineWidth', 2.0);
        axis off % Keep it clean! 
        str1 = num2str(n,'%-2i');
        text(0, -0.5, 'n = ', 'FontSize',35,'color',rgbcol);
        text(0.725, -0.5, str1, 'FontSize',35,'color',rgbcol*ampl);
        xlim([-1 6*pi+1])
        ylim([-1.4 1.4])
        frame = getframe(gcf); % Get present frame 
        writeVideo(vid,frame); % Write frame to vid 
    end
    sum = sum + y; % Add component to sum before starting the next one 
end
% Output the movie as an mp4 file and close it
close(vid);