function triangle_approximation
%
% Shows how triangle wave energy is concentrated on first harmonic
%
%   Output: triangle_approximation.eps
%

%
% Copyright (c) 2008 by Theodore P. Pavlic
%
% This work is licensed under the Creative Commons
% Attribution-Noncommercial 3.0 United States License. To view a copy of
% this license, visit http://creativecommons.org/licenses/by-nc/3.0/us/
% or send a letter to Creative Commons, 171 Second Street, Suite 300,
% San Francisco, California, 94105, USA.
%

% Upper-case    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
% Lower-case    a b c d e f g h i j k l m n o p q r s t u v w x y z
% Digits        0 1 2 3 4 5 6 7 8 9
% Exclamation   !           Double quote "          Hash (number) #
% Dollar        $           Percent      %          Ampersand     &
% Acute accent  '           Left paren   (          Right paren   )
% Asterisk      *           Plus         +          Comma         ,
% Minus         -           Point        .          Solidus       /
% Colon         :           Semicolon    ;          Less than     <
% Equals        =           Greater than >          Question mark ?
% At            @           Left bracket [          Backslash     \
% Right bracket ]           Circumflex   ^          Underscore    _
% Grave accent  `           Left brace   {          Vertical bar  |
% Right brace   }           Tilde        ~

%%%%%%%%%%%%%%%%%%%%%%%%%%% Start of Script %%%%%%%%%%%%%%%%%%%%%%%%%%% 

%%%% Generate Triangle Wave

global t triwave

% NOTE: Could use triang window to generate triwave 
t = 0:1/1000:(1-1/1000);
triwave = abs( 8*(t - 0.5) ) - 2;

t = (-1):1/1000:(1-1/1000);
triwave = [ triwave triwave ];

%%%% Plot Approximations

subplot(131);
plot_tri_approx( 4/2 );
format_title('\quad 2 Hz BPF (1 nonzero harmonic)');

subplot(132);
plot_tri_approx( 12/2 );
format_title('\quad 6 Hz BPF (3 nonzero harmonics)');

subplot(133);
plot_tri_approx( 1000/2 );
format_title('\qquad 500 Hz BPF (250 nonzero harmonics)');

%%%% Save plot

set( gcf, 'PaperType', 'usletter', ...
          'PaperOrientation', 'portrait', ...
          'PaperPosition', [0.0 3.5 11 3.5] );
saveas( gcf, 'triangle_approximation.eps', 'epsc2' );

%%%% Helper functions

    % Plots (kth fundamental) approximation and sets up axes
    function plot_tri_approx( k )
        kv = (1:k);
        approxk = (0.5-0.5*(-1).^kv) .* (8*2)./(kv*pi).^2 * cos(2*pi*kv'*t);
        plot( t, approxk, '-', t, triwave, '--' );
        xlabel( 'Time (s)', 'Interpreter', 'latex' );
    end

    % Formatted title
    function format_title( titlestr )
        title(titlestr, 'Interpreter', 'latex' );
    end

end

%%%%%%%%%%%%%%%%%%%%%%%%%%% End of Script %%%%%%%%%%%%%%%%%%%%%%%%%%% 
