% Simple Demo of cration and display of simple wavbeforms in MATLAB

close all;
clear all;

% Basic 1 period Simple Sine wave

i=0:0.2:2*pi;
y = sin(i);
figure(1)
plot(y);

%use stem(y) as alternative plot as in lecture notes to see sample values.

title('Simple 1 Period Sine Wave');


% Now Change amplitude

amp = 2.0;

y = amp*sin(i);

figure(2)
plot(y);
title('Simple 1 Period Sine Wave Modified Amplitude');


% Now change frequency

% Natural frequency is 2*pi radians

% If sample rate is F_s HZ then 1 HZ is 2*pi/F_s

% If wave frequency is F_w then freequency is F_w* (2*pi/F_s)

% set n samples steps up to sum duration nsec*F_s where nsec is the
% duration in seconds

% So we get y = amp*sin(2*pi*n*F_w/F_s);

F_s = 11025;
F_w = 440;
nsec = 2;
dur= nsec*F_s;

n = 0:dur;

y = amp*sin(2*pi*n*F_w/F_s);

figure(3)
plot(y(1:500));
title('N second Duration Sine Wave');


% To plot n cycles of a waveform

ncyc = 2;

n=0:floor(ncyc*F_s/F_w);

y = amp*sin(2*pi*n*F_w/F_s);

figure(4)
plot(y);
title('N Cycle Duration Sine Wave');


% Cosine is same as Sine (except 90 degrees out of phase)

yc = amp*cos(2*pi*n*F_w/F_s);

figure(5);
hold on
plot(yc,'b');
plot(y,'r');
title('Cos (Blue)/Sin (Red) Plot (Note Phase Difference)');
hold off;


% Square and Sawtooth Waveforms created using Radians

ysq = amp*square(2*pi*n*F_w/F_s);
ysaw = amp*sawtooth(2*pi*n*F_w/F_s);

figure(6);
hold on
plot(ysq,'b');
plot(ysaw,'r');
title('Square (Blue)/Sawtooth (Red) Waveform Plots');
hold off;


% Triangular Waveform 

delta = 2*F_w/F_s; % Half Frequency

% min and max values of simple waveform
minf=0;
maxf=1;

% create triangle wave of centre frequency values

figure(7);
hold on

ytri = [];

% plot n cycles

while(length(ytri) < floor(ncyc*F_s/F_w) )
    
    ytri = [ ytri amp*(minf:delta:maxf) ]; %upslope
    
    doplot = input('\nPlot Figure? y/[n]:\n\n', 's');

    if doplot == 'y',
       plot(ytri,'r');
       figure(7);
    end
    
    lasti = length(ytri);
    
    ytri = [ ytri amp*(maxf:-delta:minf) ]; %downslope
    
    doplot = input('\nPlot Figure? y/[n]:\n\n', 's');

    if doplot == 'y',
        plot(ytri,'b');
        figure(7);
    end
    
    
end

title('Triangular Waveform Plots');

hold off;


