dsp matlab programs
DESCRIPTION
very good to study matlabTRANSCRIPT
DSP MATLAB programs MATLAB Programs as per Exercises
This BlogLinked From HereThe WebThis Blog
Linked From Here The Web
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:lenc(i)=0;for j=1:len1if j>icontinue;endif(len2-i+j)<=0continue;endc(i)=c(i)+(x(j)*a(len2-i+j));end
endk=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 36 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); gridsubplot(3,1,2), stem(n,yt); gridsubplot(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+1if abs(h(k))<10^(-6);
breakendsum=sum+h(k);endstem(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:3x=(4*j)+y;plot(x,y)hold onendfor k=0:3;x=(4*k)-yplot(x,y)hold onendhold off**************************************%sawtooth wave generation**************************************y=0:.5:2for j=0:8a=(2*j)+yplot(a,y,'b')hold onendx=2:2:18for k=0:.01:2;b=k;plot(x,b,'b')hold onendhold off
**************************************% generation of square wave**************************************y=0:.001:2;for j=0:2:12;x=y;plot(j,x,'r');hold on;endfor k=0:4:12;x=k+y;m=2;plot(x,m,'r')hold onendfor k=2:4:12;x=k+y;m=0;plot(x,m,'r');hold on;endhold offaxis([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 fileY = fscanf(in,'%g',inf)/SF;fclose(in);if w0==0sf = SF; % scaling factor for displayelsesf = SF/N/w0;end for i=1:length(Y) if M>0 delay(2:M+1) = delay(1:M); % shift data for delayenddelay(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 signalW = W + 2*mu*E(i)*X; % update the weightsendsubplot(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==0sf = SF; % scaling factor for displayelsesf = SF/N/w0;end
in = fopen('ADF.dat','r'); %read input data from specified data fileY = fscanf(in,'%g',inf)/SF;fclose(in);
if RemoveMean % remove the mean from the data if requiredY = 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
enddelay(1) = Y(i); X(2:N) = X(1:N-1); % update bufferX(1) = delay(M+1);E(i) = Y(i) - X'*W; % the enhanced signalW = uduflt(W,X,U,E(i),gamma ,N);endsubplot(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);endb(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;endperr=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==0sf = SF; % scaling factor for displayelsesf = SF/N/w0;end
in = fopen('ADF.dat','r'); %read input data from specified data fileY = fscanf(in,'%g',inf)/SF;fclose(in);
if RemoveMean % remove the mean from the data if requiredY = 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 registersenddelay(1) = Y(i); X(2:N) = X(1:N-1); % update bufferX(1) = delay(M+1);E(i) = Y(i) - X'*W; % the enhanced signal
W = sqrtflt(W,X,E(i),S,gamma,N);endsubplot(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;endw = 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 otherwiseW = w0*ones(N,1); % adaptive filter weightsX = zeros(N,1); delay = zeros(1,M+1);P = p0*diag(ones(1,N),0);if w0==0sf = SF; % scaling factor for displayelsesf = SF/N/w0;
end
in = fopen('ADF.dat','r'); %read input data from specified data fileY = fscanf(in,'%g',inf)/SF;fclose(in);
if RemoveMean % remove the mean from the data if requiredY = 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 registersenddelay(1) = Y(i); X(2:N) = X(1:N-1); % update bufferX(1) = delay(M+1); E(i) = Y(i) - X'*W; % the enhanced signalG = P*X/(gamma + X'*P*X); P = (P - G*X'*P)/gamma; W = W + G*E(i); % update the weightsendsubplot(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 frequencyA=1.5; % relative amplitudesB=1;f1=50; % signal frequenciesf2=100;t=0:1/Fs:1; % time vectorx=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signaly=interp(x,4); % interpolate signal by 4stem(x(1:25)) % plot original signalxlabel('Discrete time, nT ')ylabel('Input signal level')figurestem(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 frequencyA=1.5; % relative amplitudesB=1;f1=50; % signal frequenciesf2=100;t=0:1/Fs:1; % time vectorx=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signaly=resample(x,4,1); % interpolate signal by 4stem(x(1:25)) % plot original signalxlabel('Discrete time, nT ')ylabel('Input signal level')figurestem(y(1:100)) % plot interpolated signal.xlabel('Discrete time, 4 x nT')ylabel('Interpolated output signal level')y1=resample(y,1,4);figurestem(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 Hzfp = 450; % passband edge frequency in Hzdp = 0.0864; % overall passband deviation in +ve dBds = 60; % overall stopband deviation in +ve dBM = 96; % overall decimation factor
EvalNStageDecimator(Fs,fp,dp,ds,M); % evaluate single stage decimatorfor i=2:4 % evaluate all possible 2-, 3- and 4-stage decimatorsR = GetFactors(M,i);for j=1:size(R,1);EvalNStageDecimator(Fs,fp,dp,ds,R(j,:));endend
===============================================% % 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;M1M2fs1fs2df1df2N1N2MPS======================================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:pfor j=2:pif n==2&i*j==MR(m,1) = i; % get the 2-stage decimator factorsR(m,2) = j;m = m + 1;elseif n>2for k=2:pif n==3&i*j*k==MR(m,1) = i; % get the 3-stageR(m,2) = j; % decimator factorsR(m,3) = k;m = m + 1;elseif n>3for l=2:pif i*j*k*l==MR(m,1) = i; % get the 4-stage R(m,2) = j; % decimator factorsR(m,3) = k;R(m,4) = l;m = m + 1;endendend
endendendendR = fliplr(sort(R')'); % sort the decimation factor vectorsz = zeros(1,size(R,2));k = 1;for i=1:size(R,1) % reject the redundanciesfor j=i+1:size(R,1)if R(i,:)==R(j,:)R(j,:) = z;endendif R(i,:)~=zDecimationFactors(k,:) = R(i,:);k = k + 1;endend
==========================================================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 stagesFIR = 0; % 1 - use FIR filter, 0 - use IIR filtern = 0; % order of IIR filter or FIR filter length% n=0 for 30 points FIR filter or 8th order Chebyshev type I LPF filterin = fopen('decimation.dat','r') ;[x,count] = fscanf(in,'%g',inf); % data to be decimatedy = x;fclose(in);for i=1:length(r)if n==0 %decimating data use default filterif FIRy = decimate(y,r(i),'fir'); elsey = decimate(y,r(i));endelseif FIRy = decimate(y,r(i),n,'fir'); elsey = decimate(y,r(i),n);endendendplot(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 decimatorsF = 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;endfprintf('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 stagesl = 4; % filter length alpha = 0.5; % cut-off frequency in = fopen('decimation.dat','r') ;[x,count] = fscanf(in,'%g',inf); % data to be decimatedy = x;fclose(in);for i=1:length(r)y = interp(y,r(i),l,alpha);endsubplot(1,2,1);stem(x);subplot(1,2,2);stem(y);
Posted by SMD at 7:06 AM 0 comments Links to this post Older Posts Home
Subscribe to: Posts (Atom)
My Links
My Profile Departmental Profile
ACADEMIC SECTION Blog Journal Crap Programs
Blog Archive
Contributors
Swanirbhar SMD
Search This Blog
powered by