You are on page 1of 24

SATURDAY, FEBRUARY 20, 2010

Correlation and Convolution

**************************************
%covolution of two sequences &
%comparison with conv command
**************************************
x=[1 4 2 4 1 1];
h=[1 2 3 4 5];
len1=length(x);
len2=length(h);
len=len1+len2-1;
a=fliplr(h);
for i=1:len
c(i)=0;
for j=1:len1
if j>i
continue;
end
if(len2-i+j)<=0
continue;
end
c(i)=c(i)+(x(j)*a(len2-i+j));
end
end
k=1:len;
conv_op1=c(1:len)
subplot(2,1,1),stem(k,conv_op1);
title('Without using "conv" command')
conv_op2=conv(x,h)
subplot(2,1,2),stem(k,conv_op2)

**************************************
% correlation using Convolution
**************************************
N = 96;
n = 1 : N;
x = cos(0.25 *pi *n);
rx = conv(x,fliplr(x));
k = -28 : 28;
subplot(5,1,1);
stem(k,rx(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title(' clean signal ACF');
w=rand(1,N)-0.5;
y=x+w;
ry=conv(y,fliplr(y));
subplot(5,1,2);
stem (k,ry(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title (' noisy signal ACF');
rw=conv(w,fliplr(w));
subplot(5,1,3);
stem(k,rw(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title(' noise ACF');
rxw=conv(x,fliplr(w));
subplot (5,1,4);
stem (k,rxw(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title (' clean signal and noise CCF');
rxy=conv(x,fliplr(y));
subplot (5,1,5);
stem (k,rxy(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title (' clean and noisy signal CCF');
**************************************
% correlation and Correlation coefficient
**************************************
N = 96;
n = 1 : N;
x = cos(0.25 *pi *n);
rx = xcorr(x);
corrcoef(x)
k = -28 : 28;
subplot(5,1,1);
stem(k,rx(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title(' clean signal ACF');
w=rand(1,N)-0.5;
y=x+w;
ry=xcorr(y);
corrcoef(y)
subplot(5,1,2);
stem (k,ry(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title (' noisy signal ACF');
rw=xcorr(w);
corrcoef(w)
subplot(5,1,3);
stem(k,rw(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title(' noise ACF');
rxw=xcorr(x,w);
corrcoef(x,w)
subplot (5,1,4);
stem (k,rxw(68 : 124));
xlabel(' log index');
ylabel(' Amplitude');
title (' clean signal and noise CCF');
rxy=xcorr(x,y);
corrcoef(x,y)
subplot (5,1,5);
stem (k,rxy(68 : 124));
xlabel(' log index');
Posted by SMD at 5:08 AM 37 comments Links to this post

Discrete Time Stable LTI Systems

**************************************
%Linearity Property of two sequences
**************************************
n=0:40; a=2; b=-3;
x1=cos(2*pi*0.1*n);
x2=cos(2*pi*0.4*n);
x=a*x1+b*x2;
ic=[0 0];
num=[2.2403 2.4908 2.2403];
den=[1 -0.4 0.75];
y1=filter(num,den,x1,ic);
y2=filter(num,den,x2,ic);
y=filter(num,den,x,ic);
yt=a*y1+b*y2;
d=y-yt;
subplot(3,1,1), stem(n,y); grid
subplot(3,1,2), stem(n,yt); grid
subplot(3,1,3), stem(n,d); grid

**************************************
%shift Invariance property
**************************************
n=0:40;D=10;
x=3*cos(2*pi*0.1*n)-2*cos(2*pi*0.4*n);
xd=[zeros(1,D) x];
num=[2.2403 2.4908 2.2403];
den=[1 -0.4 0.75];
ic=[0 0];
y=filter(num,den,x,ic)
yd=filter(num,den,xd,ic)
d=y-yd(1+D:41+D);
subplot(3,1,1),stem(y),grid;
subplot(3,1,2),stem(yd),grid;
subplot(3,1,3),stem(d),grid;

**************************************
%To check stability of a system
**************************************
num=[1 0.8];
den=[1 1.5 .9];
N=200;
h=impz(num,den,N+1);
sum=0;
n=0:N;
for k=1:N+1
if abs(h(k))<10^(-6);
break
end
sum=sum+h(k);
end
stem(n,h); grid;
disp('Value='),
disp(sum)
Posted by SMD at 5:01 AM 0 comments Links to this post

Signal Generation

**************************************
% generate unit step sequence for N=20.
%Plot discrete values and level it.
**************************************
N=20;
xn=ones(1,N);
n=0:1:N-1;
subplot(2,1,1),stem(n,xn);
subplot(2,1,2),plot(n,xn);
xlabel('n');
ylabel('xn');
title('Unit Step Sequence');
**************************************
% Plot an exponential sequence (0.7)^n
% **************************************
N=20;
n=0:1:N-1;
xn=0.7.^n;
subplot(2,1,1),stem(n,xn);
subplot(2,1,2),plot(n,xn);
xlabel('n');
ylabel('xn');
title('Exponential Sequence');
**************************************
% Plot an sinusoidal sequence
**************************************
N=50;
n=0:1:N-1;
xn=cos(0.2*pi.*n);
subplot(2,2,1),stem(n,xn);
subplot(2,2,2),plot(n,xn);
xlabel('n');
ylabel('xn');
title('Sinusoidal Sequence');
xn=sin(0.2*pi.*n);
subplot(2,2,3),stem(n,xn);
subplot(2,2,4),plot(n,xn);
xlabel('n');
ylabel('xn');
title('Sinusoidal Sequence');
**************************************
% Addition of two sinusoidal sequence
% x= sin(0.2*pi*n) + sin (0.5*pi*n)
**************************************
N=50;
n=0:1:N-1;
xn= sin(0.3*pi.*n) + sin(0.7*pi.*n);
subplot(2,1,1),stem(n,xn);
subplot(2,1,2),plot(n,xn);
xlabel('n');
ylabel('xn');
title('Addition of two Sinusoidal Sequence');
**************************************
% triangular wave generation
**************************************
y=0:0.5:2;
for j=0:3
x=(4*j)+y;
plot(x,y)
hold on
end
for k=0:3;
x=(4*k)-y
plot(x,y)
hold on
end
hold off
**************************************
%sawtooth wave generation
**************************************
y=0:.5:2
for j=0:8
a=(2*j)+y
plot(a,y,'b')
hold on
end
x=2:2:18
for k=0:.01:2;
b=k;
plot(x,b,'b')
hold on
end
hold off
**************************************
% generation of square wave
**************************************
y=0:.001:2;
for j=0:2:12;
x=y;
plot(j,x,'r');
hold on;
end
for k=0:4:12;
x=k+y;
m=2;
plot(x,m,'r')
hold on
end
for k=2:4:12;
x=k+y;
m=0;
plot(x,m,'r');
hold on;
end
hold off
axis([0 12 -0.5 2.5])
**************************************
% Aliasing
**************************************
N=100;
n=0:1:N-1;
xn=3*cos(0.2*pi.*n);
subplot(3,1,1);
plot(n,xn);
grid;
xlabel('n');
ylabel('xn');
x1n=3*cos(2.2*pi.*n);
subplot(3,1,2);
plot(n,x1n);
grid;
xlabel('n');
ylabel('x1n');
x2n=3*cos(4.2*pi.*n);
subplot(3,1,3);
plot(n,x2n);
grid;
xlabel('n');
ylabel('x2n');
title('Sinusoidal Sequence');
Posted by SMD at 4:57 AM 0 comments Links to this post

SATURDAY, JULY 18, 2009

Adaptive filters

function LMSADF
%Program to illustrate adaptive filtering using the LMS algorithms

% X delayed input data vector


% Y measured signal
% W coefficient vector
% E enhanced signal

N=30; % filter length


M=0; % delay
w0=1; % initial value for adaptive filter coefficients
SF=2048; % factor for reducing the data samples - 11 bit ADC assumed
mu=0.04;
X = zeros(N,1);
delay = zeros(1,M+1);
W = w0*ones(N,1);
in = fopen('ADF.dat','r'); %read input data from specified data file
Y = fscanf(in,'%g',inf)/SF;
fclose(in);
if w0==0
sf = SF; % scaling factor for display
else
sf = SF/N/w0;
end
for i=1:length(Y)
if M>0
delay(2:M+1) = delay(1:M); % shift data for delay
end
delay(1) = Y(i);
X(2:N) = X(1:N-1); % update buffer
X(1) = delay(M+1);
E(i) = Y(i)-W'*X; % the enhanced signal
W = W + 2*mu*E(i)*X; % update the weights
end
subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal');
subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal');

====================================================

function UDUADF
% program to illustrate adaptive filtering using
% the RLS algorithm via the UDU factorization

% X delayed input data vector


% Y measured signal
% W coefficient vector
% E enhanced signal

clear all;
N = 30; % filter length
M = 1; % delay
npt = N*(N+1)/2;
SF = 2048; % 12-bit ADC scaling
p0 = 0.05;
w0 = 1;
gamma = 0.98;
RemoveMean = 0; % 1 - remove the mean from the data, 0 - otherwise

delay = zeros(1,M);
U=zeros(1,npt);
U(1)=p0;
W = w0*ones(N,1);
X = zeros(N,1);
for i=1:N-1
ik=(i*(i+1)-2)/2+1;
U(ik)=p0;
end

if w0==0
sf = SF; % scaling factor for display
else
sf = SF/N/w0;
end

in = fopen('ADF.dat','r'); %read input data from specified data file


Y = fscanf(in,'%g',inf)/SF;
fclose(in);

if RemoveMean % remove the mean from the data if required


Y = Y - sum(Y)/length(Y);
end

for i=1:length(Y)
if M>0
delay(2:M+1) = delay(1:M); % shift input data in delay registers
end
delay(1) = Y(i);
X(2:N) = X(1:N-1); % update buffer
X(1) = delay(M+1);
E(i) = Y(i) - X'*W; % the enhanced signal
W = uduflt(W,X,U,E(i),gamma ,N);
end
subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal');
subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal');

==========================================
function w=uduflt(w,x,u,ek,gamma,N)

% udu algorithm - a numerically stable form of


% the recursive least squares algorithm
%
% inputs:
% x() input vector
% dn latest input data value
% w() coefficient vector
% u() vector containing elements of U and D
%
% outputs:
% en error signal
% yn digital filter output
% w() updated coefficient vector
% u() updated elements of U and D
%

sf = 1/gamma;

m=1; % update the UD elements


v=zeros(1,N);
v(1)=x(1);
for j=2:N
v(j)=x(j);
for k=1:j-1
m=m+1;
v(j)=v(j)+u(m)*x(k);
end
m=m+1;
b(j)=u(m)*v(j);
end
b(1)=u(1)*x(1);
alpha=gamma+b(1)*v(1);
delta=1/alpha;
u(1)=u(1)*delta;

m=1;
for j=2:N
beta1=alpha;
alpha=alpha+b(j)*v(j);
p=-v(j)*delta;
delta=1/alpha;
for k=1:j-1
m=m+1;
beta=u(m);
u(m)=beta+b(k)*p;
b(k)=b(k)+b(j)*beta;
end
m=m+1;
u(m)=u(m)*beta1*delta*sf;
end
perr=ek/alpha;
for j=1:N % update the weights
w(j)=w(j)+b(j)*perr;
end

============================================
function SQRTADF
% program to illustrate adaptive filtering using
% the square root RLS algorithm
% X delayed input data vector
% Y measured signal
% W coefficient vector
% E enhanced signal

N = 30; % filter length


M = 1; % delay
npt = N*(N+1)/2;
SF = 2048; % 12-bit ADC scaling
p0 = 0.05;
w0 = 1;
gamma = 0.98;
RemoveMean = 0; % 1 - remove the mean from the data, 0 - otherwise

delay = zeros(1,M);
W = w0*ones(N,1);
X = zeros(N,1);
S = zeros(1,npt);
S(1)=p0;
for i=1:N-1
ik=(i*(i+1)-2)/2+1;
S(ik)=p0;
end

if w0==0
sf = SF; % scaling factor for display
else
sf = SF/N/w0;
end

in = fopen('ADF.dat','r'); %read input data from specified data file


Y = fscanf(in,'%g',inf)/SF;
fclose(in);

if RemoveMean % remove the mean from the data if required


Y = Y - sum(Y)/length(Y);
end

for i=1:length(Y)
if M>0
delay(2:M+1) = delay(1:M); % shift input data in delay registers
end
delay(1) = Y(i);
X(2:N) = X(1:N-1); % update buffer
X(1) = delay(M+1);
E(i) = Y(i) - X'*W; % the enhanced signal

W = sqrtflt(W,X,E(i),S,gamma,N);
end
subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal');
subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal');

==================================================

function w=sqrtflt(w,x,perr,s,gamma,N)

% A simple square root RLS adaptive filter


% For details, see:
% Digital Signal Processing: A Practical Approach
% E C Ifeachor and B W Jervis, Pearson, 2002

forgt=sqrt(gamma);
sig=forgt;
sigsq=forgt*forgt;
ij=1; ji=1;
for j=2:N
fj=0.0;
for i=1:j-1
ji=ji+1;
fj=fj+s(ji)*x(i);
end
a=sig/forgt;
b=fj/sigsq;
sigsq=sigsq+fj*fj;
sig=sqrt(sigsq);
a=a/sig;
g(j)=s(ji)*fj;
s(ji)=a*s(ji);
for i=1:j-1
ij=ij+1;
sqp=s(ij);
s(ij)=a*(sqp-b*g(i));
g(i)=g(i)+sqp*fj;
end
ij=ij+1;
end
w = w + g'*perr/sigsq;

=============================
function RLSadf
% program to illustrate adaptive filtering using
% the RLS algorithm

% X delayed input signal


% Y measured signal
% W coefficient vector
% E enhanced signal

N = 30; % filter length


M = 1; % stages of delay
SF = 2048; % 12-bit ADC scaling
p0 = 0.05;
w0 = 100;
gamma = 0.98;
RemoveMean = 0; % 1 to remove the mean, 0 otherwise
W = w0*ones(N,1); % adaptive filter weights
X = zeros(N,1);
delay = zeros(1,M+1);
P = p0*diag(ones(1,N),0);
if w0==0
sf = SF; % scaling factor for display
else
sf = SF/N/w0;
end

in = fopen('ADF.dat','r'); %read input data from specified data file


Y = fscanf(in,'%g',inf)/SF;
fclose(in);

if RemoveMean % remove the mean from the data if required


Y = Y - sum(Y)/length(Y);
end

for i=1:length(Y)
if M>0
delay(2:M+1) = delay(1:M); % shift input data in delay registers
end
delay(1) = Y(i);
X(2:N) = X(1:N-1); % update buffer
X(1) = delay(M+1);
E(i) = Y(i) - X'*W; % the enhanced signal
G = P*X/(gamma + X'*P*X);
P = (P - G*X'*P)/gamma;
W = W + G*E(i); % update the weights
end
subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal');
subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal');
Posted by Swanirbhar at 7:10 AM 2 comments Links to this post

Multirate digital signal processing

% % m-file to illustrate simple interpolation and


% decimation operations (Program 9B.1, p641)
% File name: prog9b1.m
% An Illustration of interpolation by a factor of 4 %
Fs=1000; % sampling frequency
A=1.5; % relative amplitudes
B=1;
f1=50; % signal frequencies
f2=100;
t=0:1/Fs:1; % time vector
x=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signal
y=interp(x,4); % interpolate signal by 4
stem(x(1:25)) % plot original signal
xlabel('Discrete time, nT ')
ylabel('Input signal level')
figure
stem(y(1:100)) % plot interpolated signal.
xlabel('Discrete time, 4 x nT')
ylabel('Output signal level')
==========================================

% % m-file to illustrate simple interpolation and


% decimation operations (Program 9B.2, p644).
% File name: prog9b2.m
% An Illustration of sampling rate changes using upfirdn by a factor of 4
%
Fs=1000; % sampling frequency
A=1.5; % relative amplitudes
B=1;
f1=50; % signal frequencies
f2=100;
t=0:1/Fs:1; % time vector
x=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signal
y=resample(x,4,1); % interpolate signal by 4
stem(x(1:25)) % plot original signal
xlabel('Discrete time, nT ')
ylabel('Input signal level')
figure
stem(y(1:100)) % plot interpolated signal.
xlabel('Discrete time, 4 x nT')
ylabel('Interpolated output signal level')
y1=resample(y,1,4);
figure
stem(y1(1:25)) % plot decimated signal.
xlabel('Discrete time, nT')
ylabel('Decimated output signal level')

============================================
function moptimum
%Program moptimum is for designing I-stage optimum decimator
%or interpolator (I=1,2,3 or 4). The program computes the decimation
%factors, filter characteristics, and decimator efficiencies

%The following parameters must be provided by the user:


% Fs - input sampling frequency
% M - overall decimation factor
% fp - passband edge frequency
% dp - overall passband deviation in +ve dB
% ds - overall stopband deviation in +ve dB

clear all;
Fs = 96000; % sampling frequency in Hz
fp = 450; % passband edge frequency in Hz
dp = 0.0864; % overall passband deviation in +ve dB
ds = 60; % overall stopband deviation in +ve dB
M = 96; % overall decimation factor

EvalNStageDecimator(Fs,fp,dp,ds,M); % evaluate single stage decimator


for i=2:4 % evaluate all possible 2-, 3- and 4-stage decimators
R = GetFactors(M,i);
for j=1:size(R,1);
EvalNStageDecimator(Fs,fp,dp,ds,R(j,:));
end
end
===============================================
% % m-file for working out the computational
% complexities of a 2-stage decimator % Program name: mrate-ex1.m %
dp=0.01;
ds=0.01;
dp1=dp/2;
ds1=ds;
fp=5000;
Fi=1536000; F0=12000;
M=Fi/F0; M1=16; M2=8;
F1=Fi/M1; F2=F1/M2;
fs1=F1-(Fi/(2*M)); fs2=F2-(Fi/(2*M));
df1=(fs1-fp)/Fi; df2=(fs2-fp)/F1;
NUM= -10*log10(dp1*ds1)-13;
N1=(NUM/(14.6*df1)); N2=(NUM/(14.6*df2));
MPS=(N1*F1 + N2*F2); TSR = N1+N2;
M1
M2
fs1
fs2
df1
df2
N1
N2
MPS
======================================
function DecimationFactors = GetFactors(M,n)
% The function GetFactors finds all possible decimation factors for
% 2-, 3-, and 4-stage decimation. M is the
% overall decimation factor and n is the number of stages

p = floor(M/(2^(n-1)));
m = 1;
for i=2:p
for j=2:p
if n==2&i*j==M
R(m,1) = i; % get the 2-stage decimator factors
R(m,2) = j;
m = m + 1;
elseif n>2
for k=2:p
if n==3&i*j*k==M
R(m,1) = i; % get the 3-stage
R(m,2) = j; % decimator factors
R(m,3) = k;
m = m + 1;
elseif n>3
for l=2:p
if i*j*k*l==M
R(m,1) = i; % get the 4-stage
R(m,2) = j; % decimator factors
R(m,3) = k;
R(m,4) = l;
m = m + 1;
end
end
end
end
end
end
end
R = fliplr(sort(R')'); % sort the decimation factor vectors
z = zeros(1,size(R,2));
k = 1;
for i=1:size(R,1) % reject the redundancies
for j=i+1:size(R,1)
if R(i,:)==R(j,:)
R(j,:) = z;
end
end
if R(i,:)~=z
DecimationFactors(k,:) = R(i,:);
k = k + 1;
end
end

==========================================================
function decimation
%program performs multi-stages of decimation on data in a user-specified data file
%enough data must be guaranteed when using a large overall decimation fator

clear all;

r = [2 2 3 2]; % decimation factor array for different stages


FIR = 0; % 1 - use FIR filter, 0 - use IIR filter
n = 0; % order of IIR filter or FIR filter length
% n=0 for 30 points FIR filter or 8th order Chebyshev type I LPF filter
in = fopen('decimation.dat','r') ;
[x,count] = fscanf(in,'%g',inf); % data to be decimated
y = x;
fclose(in);
for i=1:length(r)
if n==0 %decimating data use default filter
if FIR
y = decimate(y,r(i),'fir');
else
y = decimate(y,r(i));
end
else
if FIR
y = decimate(y,r(i),n,'fir');
else
y = decimate(y,r(i),n);
end
end
end
plot(1:count,x,1:prod(r):count,y(1:length(y)),'o');
===========================================================
function EvalNStageDecimator(Fs,fp,dp,ds,R)
format long;
a1 = 0.005309;
a2 = 0.07114;
a3 = -0.4761;
a4 = -0.00266;
a5 = -0.5941;
a6 = -0.4278;
a7 = 11.01217;
a8 = 0.51244;
dp = 10^(dp/20.0)-1; ds = 10^(-ds/20.0);
Ftemp = Fs;

dp = dp/length(R);
MPS = 0; TSR = 0;
fprintf('stage\tfactor\tFi\tfp\tfs\tdp\tds\tN\n');
for i=1:length(R) % n=size(R,1) possible k-stages decimators
F = Ftemp/R(i);
fs = F - Fs/2/prod(R);
df = (fs - fp)/Ftemp;
Ftemp = F;
N = round((log10(ds)*(a1*log10(dp)^2+a2*log10(dp)+a3)+...
a4*log10(dp)^2+a5*log10(dp)+a6)/df-df*(a7+a8*(log10(dp)-log10(ds)))+1);
fprintf('%d\t%d\t%d\t%d\t%d\t%-7.4f\t%-7.4f\t%d\n',i,R(i),F,fp,fs,dp,ds,N);
MPS = MPS + N*F;
TSR = TSR + N;
end
fprintf('MPS = %d, TSR = %d\n\n',MPS,TSR);
format;

========================
function interpolation
%program performs multi-stages interpolation on data in a user-specified data file
clear all;

r = [2 1 1]; % decimation factor array for different stages


l = 4; % filter length
alpha = 0.5; % cut-off frequency
in = fopen('decimation.dat','r') ;
[x,count] = fscanf(in,'%g',inf); % data to be decimated
y = x;
fclose(in);
for i=1:length(r)
y = interp(y,r(i),l,alpha);
end
subplot(1,2,1);stem(x);subplot(1,2,2);stem(y);

You might also like