% Matlab script to demonstrate creation of square and impulse train
% waveforms from a sawtooth waveform.
%
% by Gary Scavone, McGill University, 2025.

M = 1000;  % table size
stt = linspace(0, 1, M); % sawtooth table

N = 5000;  % number of samples to compute
y1 = zeros(1, N);
y2 = zeros(1, N);
ptr1 = 1;
ptr2 = M/2;
for n = 1:N
  y1(n) = stt(ptr1); % sawtooth
  y2(n) = stt(ptr1) - stt(ptr2); % square
  ptr1 = ptr1 + 1;
  ptr2 = ptr2 + 1;
  if ptr1 > M, ptr1 = 1; end
  if ptr2 > M, ptr2 = 1; end
end

subplot(1, 2, 1)
plot(-diff(y1))
xlabel('Time (samples)');
ylabel('Amplitude');
title('Differentiated sawtooth')
subplot(1, 2, 2)
plot(y2)
xlabel('Time (samples)');
ylabel('Amplitude');
title('Saw added to delayed, inverted saw')
