% A Matlab script to create and play some distorted sinusoidal signals.
%
% by Gary Scavone, McGill University, 2025.

clf
fs = 44100;
Ts = 1 / fs;
Dur = 2.0;
t = 0:Ts:Dur;
f = 440;

x = sin(2*pi*f*t);

% Hard clipper
L = 0.7;
y = x;
y(y > L) = L;
y(y < -L) = -L;

plot(t, [x; y].')
xlabel('Time (seconds)')
ylabel('Signal Amplitude')
legend('Sinusoid', 'Hard Clipped')

% soundsc([x zeros(1, fs/4) y], fs)

disp('paused ...')
pause

% Soft clipper
G = 2;
y = sign(x).*(1 - exp(-G*abs(x)));

plot(t, [x; y].')
xlabel('Time (seconds)')
ylabel('Signal Amplitude')
legend('Sinusoid', 'Soft Clipped')

% soundsc([x zeros(1, fs/4) y], fs)

disp('paused ...')
pause
 
% Polynomial function
y = (x + x.^3 + x.^5 + x.^7);
y = y / max(y);

plot(t, [x; y].')
xlabel('Time (seconds)')
ylabel('Signal Amplitude')
legend('Sinusoid', 'Polynomial')

% soundsc([x zeros(1, fs/4) y], fs

% Buchla 259 function
x = 5 * x;
y = x;
y(y > 1) = x(x>1) - 2;
y(y < -1) = y(y < -1) + 2;
y = y / max(y);

plot(t, [x/5; y].')
xlabel('Time (seconds)')
ylabel('Signal Amplitude')
legend('Sinusoid', 'Buchla 259')

% soundsc([x/5 zeros(1, fs/4) y], fs