% sineplot.m
% plot sampled sine wave and filter

clear all;close all;

fs=8000; % sampling frequency
Ts=1/fs; % sampling time
f=1000;  % frequency of sine wave

n=(0:16); % sample number (sample index)
x1=sin(2*pi*f*n*Ts); % x1 is a function of n

t=linspace(0,0.002,17); % time in seconds
x2=sin(2*pi*f*t); % x2 is a function of t

tau=(0:1/8000:2/1000); % time in seconds
x3=sin(2*pi*f*tau); % x3 is a function of tau

% x1=x2=x3

% definition of derivative
% y(t)=[x(t)-x(t-delta_t)]/delta_t
% where t is the time in seconds
% and delta_t is the sampling time Ts
% since t is sampled at intervals of Ts, we can write t=nTs, and 
% y(nTs)=[x(nTs)-x((n-1)Ts)]/Ts
% this will give the correct numerical derivative
% can also refer to sample number n only (omitting Ts) and write
% y(n)=x(n)-x(n-1)
% in this case, the derivative is not scaled to Ts

b=[1 -1]; % filter coefficients
y3=filter(b,1,x1); % implements y(n)=b(1)*x(n)+b(2)*x(n-1)
                  % which in this case is y(n)=x(n)-x(n-1)
figure(1);
plot(t,x1,'b-o');  % plots x1 versus t  
hold on;
plot(t,y3,'r-o');
hold off;

figure(2)
plot(x1,'b-o');  % plots x1 versus sample number n 
hold on;
plot(y3,'r-o');

a=[1 -0.9];  
b=[1];
y4=filter(b,a,x1); % implements a(1)*y(n)+a(2)*y(n-1)=b(1)*x(n)  
             % which may be written y(n)-0.9y(n-1)=x(n) 
             % or y(n)=0.9y(n-1)+x(n)

figure(4);
plot(t,x1,'b-o');  % plots x1 versus t  
hold on;
plot(t,y4,'m-o');
hold off;