% experiment with sound and signals

fs = 8192;
t = 0: 1 / fs: 1;
x = .5 * cos(440 * 2 * pi * t);  
%sound(x,fs)
subplot(221); plot(t,x)
axis([0 .01 -1 1])


x1 = .5 + x;  % what happens if you add a DC component
%sound(x1,fs)
subplot(222),plot(t, x1)
title('.5 +.5cos(440(2pi)t)')
axis([0 .01 -1 1])
pause

x2 = x +.5 * cos(880 * 2 * pi * t);  % what happens when you add a harmonic
%sound(x2, fs)
subplot(223),plot(t, x2)
title('.5(cos(440(2pi)t+cos(880(2pi)t))')
axis([0 .01 -1 1])
pause

% now add several harmonics with equal magnitude
x3 = x2+.5*cos(440*3*2*pi*t)+.5*cos(440*4*2*pi*t)+.5*cos(440*5*2*pi*t);
x3 = x3*.4;  % scale to avoid clipping
%sound(x3, fs)
subplot(224),plot(t,x3)
title('Equal Harmonics')
axis([0 .01 -1 1])
pause

figure(2)
% now consider several harmonics with decreasing magnitude
x4 = .4 * cos(440 * 2 * 2 * pi * t) + .3 * cos(440 * 3 * 2 * pi * t);
x4 + x4 + .2 * cos(440 * 4 * 2 * pi * t) + .1 * cos(440 * 5 * 2 * pi * t);
x4 = x4 * .6;  %scale to avoid clipping
%sound(x4,fs)
subplot(221),plot(t, x4)
title('Decreasing Harmonics')
axis([0 .01 -1 1])
pause

% Square wave I
w = 440 * 2 * pi;
N = 50;
xN = zeros(size(t));
tic
for n = 1:2:N
  xN = xN + 1 / n * cos(n * w * t + pi / 2);
end
toc
%sound(xN,fs)
subplot(221),plot(t, xN)
title('Square Wave')
axis([0 .01 -1 1])
pause

% Square wave II
w = 440 * 2 * pi;
N = 50;
xN = zeros(size(t));
tic
for n = 1:2:N
  xN = xN + 1 / n * (exp(j * n * w * t) - exp(-j * n * w * t)) / (2 * j);
end
toc
%sound(xN,fs)
subplot(222),plot(t, xN)
title('Square Wave')
axis([0 .01 -1 1])
pause

% Square wave III
w = 440 * 2 * pi;
N = 25;
xN = zeros(size(t));
n = 1:N;
tic
cn =  1 ./ n / pi .* sin(n * pi / 2);  
xN = cn * (exp(j * n' * w * t) + exp(-j * n' * w * t));
toc
%sound(xN,fs)
subplot(223),plot(t,xN)
title('Square Wave')
axis([0 .01 -1 1])

% pure sqaure wave
T = 1 / 440;
tmp = mod(t, T);
x7 = (tmp < T / 2) - 0.5;
subplot(224),plot(t,x7)
title('Pure Square Wave')
axis([0 .01 -1 1])

% built-in square()

x = square(440 * 2 * pi * t);, plot(t, x), axis([0 .01 -2 2]);
duty = 20;
x = square(440 * 2 * pi * t, duty);, plot(t, x), axis([0 .02 -2 2]);


figure(3)
% example of amplitude modulation (beating)
x5 = cos(10 * 2 * pi * t) .* cos(440 * 2 * pi * t);
subplot(121), plot(t,x5)
xlabel('Time (sec)')
axis([0 .2 -1 1])
ylabel('x(t)')
title('Amplitude Modulation')
%sound(x5, fs)
pause

% example of chirp signal (frequency changes over time)
f = 1000 * t + 440;  
x6 = cos(f .* t);
subplot(122), plot(t, x6)
title('Chirp Signal')
xlabel('Time (Sec)')
ylabel('x(t)')
axis([0 .3 -1 1])
%sound(x6, fs)
figure(4)
specgram(x6,512,8192,256)

x = chirp(t, 0, 1, 4000); specgram(x,512,8192,256);

% Pulse train
T = 0:1/50E3:10E-3;
D = [0:1/1E3:10E-3;0.8.^(0:10)]';
Y = pulstran(T,D,'gauspuls',10E3,0.5);
plot(T,Y)

% sinc sin(pi * x) / (pi * x)
x = linspace(-5,5);
y = sinc(x);
plot(x,y)
