% tabletest.m
%
% A simple example script to demonstrate a sinusoidal wavetable with
% truncation, rounding and linear interpolation.
%
% by Gary Scavone, McGill University.

clear
fs = 44100;  % sample rate
Ts = 1 / fs; % sample period

N = 512;     % table length
t = sin(2*pi*(0:N-1)/N);

M = 40000;       % length of sound to compute
y = zeros(1, M); % output sound vector
ptr = 1;         % sample pointer

f0 = 540;         % desired sinusoidal frequency
p = N * f0 * Ts;  % pointer increment

type = 3; % 1 = truncation, 2 = rounding, 3 = linear interpolation

for n = 1:M
  if type == 1 % truncation
    y(n) = t(floor(ptr));
    ptr = ptr + p;
    if floor(ptr) > N, ptr = ptr - N; end
  elseif type == 2 % rounding
    y(n) = t(round(ptr));
    ptr = ptr + p;
    if round(ptr) > N, ptr = ptr - N; end
  else % linear interpolation
    yf = t(floor(ptr));
    delta = ptr - floor(ptr);
    cptr = ceil(ptr);
    if (cptr > N ), cptr = cptr - N; end
    yc = t(cptr);
    y(n) = delta*(yc - yf) + yf;
    ptr = ptr + p;
    if floor(ptr) > N, ptr = ptr - N; end
  end
end

f = fs*(0:M-1)/M;
plot( f, 20*log10(abs(fft(y))) );
xlim([0 15000])
grid
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)')