Sunteți pe pagina 1din 10

MATLAB PRACTICE

% Basic Matlab Tutorial % Tutorial 1 - Variable Definition and Plotting close all; clear all; clc; x=1:1:100; % Define a 1 Dimensional Array of Values y=x.^2; % Use of Dot Operator - Element by Element z=sqrt(x); % Square Root Operation figure(1) % Open Figure Window - Label it Figure 1 plot(x,y,'r.') % Plot X vs Y with Red Dots grid on % Turns on Grid Background xlabel('X - Axis') % X - Axis Label ylabel('Y - Axis') % y - Axis Label title('First Plot of X^2') % Chart Title % Refer to "help plot" in Matlab for more plotting options figure(2) % Open Figure Window - Label it Figure 1 plot3(x,y,z,'ko') % Plot [X,Y,Z] with Black Circles grid on % Turns on Grid Background xlabel('X - Axis') % X - Axis Label ylabel('Y - Axis') % Y - Axis Label zlabel('Z - Axis') % Z - Axis Label title('Second Plot of X^2') % Chart Title %axis([xmin xmax ymin ymax zmin zmax]); % Zoom to Limited Axis figure(3) subplot(2,1,1); plot(x,y,'r.') % Subplot(# Rows, # Cols, Select) title('Use of the Subplot command') subplot(2,1,2); plot(x,z,'b.')

Impulse FUNCTION

function[x,n]=impseq(n0,n1,n2) n=[n1:n2] x=[(n-n0)==0] stem(n,x) xlabel('n') ylabel('x') title('Unit sample sequence')

Step Function
function[x,n]=stepseq(n0,n1,n2) %Generates x(n)=u(n-n0);n1<=n<=n2 n=[n1:n2] x=[(n-n0)>=0] %stem(n,x) plot(n,x) xlabel('n') ylabel('x') title('Unit step sequence')

Plotting sine function

% Figure 1.13 % gives example of a continuous-time signal t=0:0.1:30; x = exp(-.1*t).*sin(2/3*t); plot(t,x) grid axis([0 30 -1 1]); ylabel('x(t)') xlabel('Time (sec)') title('Figure 1.13')

Sum of sinusoids

Exp 6

%TO Find SUM of 4 SINUSOIDAL waves of 4 different amplitudes %SINE with amplitude 2 t=0:0.001:5; A=20; x=A*sin(2*pi*t); subplot(2,2,1) plot(t,x) title('sine wave with amplitude 2') xlabel('time') ylabel('amp') %SINE with amplitude 4 t1=0:0.001:10 B=40; y=B*sin(2*pi*t1); subplot(2,2,2) plot(t1,y) title('sine with amp 4') xlabel('time') ylabel('AMP') %sine with amplitude 10 t2=0:0.001:2 C=10; z=C*sin(2*pi*t2); subplot(2,2,3) plot(t2,z) title('sine with amp 10') xlabel('time') ylabel('AMP') %sine with amplitude 0.5 t3=0:.001:20; D=0.05; W=D*sin(2*pi*t3); subplot(2,2,4) plot(t3,W) title('sine with amp 0.5') xlabel('time') ylabel('AMP') %addition of all the above sinusoids x1=padarray(x,[0,15000],0,'post'); y1=padarray(y,[0,10000],0,'post'); z1=padarray(z,[0,18000],0,'post'); v=x1-y1-z1-W; t4=0:.001:20; figure,plot(t4,v) title('sum of sines') xlabel('time') ylabel('amp')

Low pass filter using Z-transform EXP 7


%Run from editor Debug(F5) %This M file constructs a low pass filter using the Z Transform and %analyzes the characteristics of the filter such as frequency response and %phase using the Matlab filter function with input vector x %to get output y=filter(b,a,x).Frequency domain plots are also provided. %The z transform is just basically a transformation from a linear system to %a sampled system. %The -3dB points of the filter can be set to <100Hz to >1GHz by appropriate %setting of the sampling frequency(fs) and f. The purpose of constructing this M file was %instigated by the following facts. I have some knowledge of Laplace %transforms and the s plane. Someone mentioned using z transforms and I %said "What is a z transform, that sounds complicated?". Anyway, that's why. %I have added references at the end of the program that I have found %helpful and hopefully playing with the program will give you a better %understanding of the theory. Always remember to set your axis settings on %plot routines. %Low pass filter 1 pole 1 zero %H(z)=z+1/z-p %zero at -1 %pole at -1<x<1 % % % Z plane !+j(imag axis) % ! % ! %1 pole & 1 zero (-1)0---------!-------x--(+1)real axis % ! % ! % !-j % %I should note that the H(z)=z/z-p transform also produces a low pass filter %but is not as efficient as the one shown here. It has a zero at 0 and a %pole from 0<x<1. It becomes a high pass filter with -1<x<0. You can %observe this at the JDSP site using the pole-zero demo. %Design example %~.45Mhz -3dB point %fs=1000000 clear fs=1000000;%sample frequency %f/fs=.5,f=500000 f=[0:5000:500000];%keep interval steps high for lower %computer processing time Fn=fs/2;%nyquist frequency w=2*pi*f/fs;%set so w=pi or 3.14 z=exp(w*j);%z definition p=-.7;%change values for different filter -3dB bandwidths,(-.99 to .99) gain=.85;%set gain for unity(1) with gain=(1-(p))/2 Hz=gain*(z+1)./(z-(p));%z transform %=================================================== %Magnitude and phase plots %=================================================== figure(1) subplot(3,1,1), plot(f,abs(Hz)) axis([0 1000000 0 1.5]); grid on title('Magnitude Response of H(z)') ylabel('H(z)-voltage') subplot(3,1,2); Hz(Hz==0)=10^(-8);%avoid log(0) plot(f,20*log10(abs(Hz))); grid on ylabel('dB') axis([0 1000000 -3 1]);

subplot(3,1,3), plot(f,angle(Hz)) grid on title('Phase Response of H(z)') ylabel('radians*57.3=degrees')%one radian=57.3 degrees xlabel('f [Hertz]') axis([0 1000000 -2 0]); fc=443000;%carrier frequency(Hz) T=1/200;%sets span of y filter output plot %x=A1*(cos(2*pi*fc*t)+phi)(cosine wave) twopi_fc_t=(1:fs*T)*2*pi*fc/fs; A1=1; phi=0; x = A1 * cos(twopi_fc_t + phi); %you could also use a square wave or an impulse signal insteat of a cosine %wave. %=============================================== %a and b filter coefficients %=============================================== a=[1 .7];%(z-(p)) b=[.85 .85];%gain times [1 1) % =============================================== %Output y = filter(b,a,x) % =============================================== y = filter(b,a,x); %plot input x and output y %observe amplitude and phase shift of y compared to x. Will need %much lower -3dB point filter(say 200Hz) and span to see phase shift. Notice 1Vp(input) to %.7Vp(output) for -3dB point. Magnitude and phase shift at fc shown in %command window. figure(2); plot(x,'b-'); hold on; plot(y,'r-'); grid on title('input x(blue) / output y(red)') ylabel('Voltage') hold off; %Magnitude and phase at fc w=2*pi*fc/fs; z=exp(w*j); Hz=gain*(z+1)./(z-(p)); magfc=abs(Hz) phaseradfc=angle(Hz)

Band Pass Filter in Z-Transform EXP 8


%This M file constructs a two pole two zero bandpass filter using the Z Transform %transfer function and analyzes the characteristics of the filter such as frequency response and %phase using the Matlab filter function with input vector x %to get output y=filter(b,a,x).Frequency domain plots are also provided to %analyze the bandpass filter. %The z transform is just basically a transformation from a linear continuous system to %a sampled system. %The center frequency and 3dB bandwidth(fBW) of the BPF filter can be set to %<100Hz to >1GHz by appropriate setting of the sampling frequency(fs) and %center frequency(fcent) and by use of the following formula(BW=(1-a)/sqrt(a)) where %BW=2*pi*fcent/fs and (a) is the imaginary pole magnitudes. To get 0dB of attenuation %at the center frequency(fcent),the poles must be at an angle of 2*pi*fcent/fs=pi/2. %This corresponds to +/-j on the unit circle in the z domain. The symbolic math %processor in Matlab is used with the "solve" function to determine the %value as shown typed in the command window "solve('2*(1-a)/sqrt(a)=BW')". %Bandpass filter 2 poles 2 zeros %H(z)=(z+1)*(z-1)/(z+jp)*(z-jp)=(z^2-1)/(z^2-(p^2) %zeros at +/-1 %pole at +j/-j % % pi/2 % Z plane !+j(imag axis) % x % fs/2 ! %2 poles,2 zeros (-1)0---------!---------(+1)real axis % pi ! % x % !-j % % %================================================== %Design example %================================================== clear fcent=6500e6;%center frequency of bandpass filter fBW=1000e6;%3dB bandwidth fs=26e9;%sampling frequency(set ~4 times fcent) %f/fs=.5,set f=.5*fs f=[0:1e6:13e9];%keep interval steps high for lower %computer processing time Fn=fs/2;%nyquist frequency-used in fft plots w=2*pi*f/fs;%set so w=pi or 3.14 z=exp(w*j);%z definition BW=2*pi*fBW/fs; %solve('2*(1-a)/sqrt(a)=BW')%-solving for a gives a=.8862 %One could also use the symbolic math processor and construct a graph to %solve for (a). %type in command window the following: %syms BW a %BW=(2*(1-a)/sqrt(a)) %ezplot(BW),axis([0 1 0 1]),ylabel('BW'),grid on a=.8862; p=(j^2*a^2);%multiply (j*a)*(-j*a) gain=.105;%set gain for unity(1) by observing plots Hz=gain*(z+1).*(z-1)./(z.^2-(p));%z transform(transfer function) %=================================================== %Magnitude and phase plots %=================================================== figure(1) subplot(3,1,1), plot(f,abs(Hz)) axis([0 13e9 0 1.5]); grid on title('Magnitude Response of H(z)') ylabel('H(z)-voltage')

subplot(3,1,2); Hz(Hz==0)=10^(-8);%avoid log(0) plot(f,20*log10(abs(Hz))); grid on ylabel('dB') axis([0 13e9 -3 1]);%set -3 to -60 to zoom out subplot(3,1,3), plot(f,angle(Hz)) grid on title('Phase Response of H(z)') ylabel('radians*57.3=degrees')%one radian=57.3 degrees xlabel('f [Hertz]') axis([0 13e9 -2 2]); fcent=6500e6;%carrier frequency(Hz),notice no loss at 6500e6 %Try 6000e6 and 7000e6 to check for -3dB loss. T=1/1e6;%sets span of y filter output plot %x=A1*(cos(2*pi*fc*t)+phi)(cosine wave) twopi_fc_t=(1:fs*T)*2*pi*fcent/fs; A1=1; phi=0; x = A1 * cos(twopi_fc_t + phi); %You could also use a square wave or an impulse signal instead of a cosine %wave. %=============================================== %a and b filter coefficients %=============================================== %To get the a and b coefficients, expand the numerator and denominator. %a=(z+p)*(z-p)=z^2-(p^2)=[1 0 -(p)] a=[1 0 .7855];%(1 0 p) b=[.105 0 -.105];%gain times [1 0 -1) % =============================================== %Output y = filter(b,a,x) % =============================================== y = filter(b,a,x); %Plot input x and output y %Observe amplitude and phase shift of y compared to x. Will need %much lower center frequency bandpass filter(say 1000Hz) and span to see phase shift. %Magnitude and phase shift at fc shown in command window. figure(2); plot(x,'b-'); hold on; plot(y,'r-'); grid on title('input x(blue) / output y(red)') ylabel('Voltage') hold off; %Magnitude and phase at fcent w=2*pi*fcent/fs; z=exp(w*j); Hz=gain*(z+1).*(z-1)./(z.^2-(p)); magfcent=abs(Hz) phaseradfcent=angle(Hz)

Butterworth and chebyshev Analog filter design EXP 9


% This program Designs a filter % Plots the impulse & step response and computes the transfer function % For Butterworth & Chebyshev Approximations % Specify filter type fprintf('\n Enter the Approximation method You will use') type = input('\n Enter (b) for Butterworth Approximation or (c) for Chebyshev : ','s'); if (type == 'b') fprintf('\n You choose Butterworth Approximation : ') way = input('\n Enter (o) if You know the order or (d) for a filter design : ','s'); if (way == 'd') wr = input('\n Enter the normalized Rejection frequency : '); att = input('\n Enter the Attenuation value at this frequency in dB : '); n = att / (20 * log10(wr)); n = ceil(n); fprintf('\n The order of the filter is %d',n) elseif (way == 'o') n = input('\n Enter the order of Butterworth filter : '); else fprintf('\n Sorry! You entered a wrong choice'); end % Get the poles for k = 1 : 2*n thepoles(k) = exp(j*pi*((2*k+n-1)/(2*n))); if (real(thepoles(k)) >= 0) thepoles(k) = 0; end end hh = find(thepoles); stpoles = thepoles(hh); % Stable Poles elseif (type == 'c') fprintf('\n You choose Chebyshev Approximation : ') way = input('\n Enter (o) if You know the order & ripple factor or (d) for a filter design : ','s'); if (way == 'd') ripples = input('\n Enter the Ripples value of the passband in dB : '); wr = input('\n Enter the normalized Rejection frequency : '); att = input('\n Enter the Attenuation value at this frequency in dB : '); po = ripples / 10; const = 10 .^ po; eibsln = sqrt((const - 1)); n = (att + 6 - 20 * log10(eibsln)) / (6 + 20 * log10(wr)); n = ceil(n); fprintf('\n The order of the filter is %d',n) fprintf('\n The value of ripple factor is %d',eibsln) elseif (way == 'o') n = input('\n Enter the order of Chebyshev filter : '); eibsln = input('\n Enter the ripple factor of the passband : '); else fprintf('\n Sorry! You entered a wrong choice'); end v = (1/n) * asinh(1/eibsln); siv = sinh(v); cov = cosh(v); % Get the poles for k = 1 : 2*n thepoles(k) = exp(j*pi*((2*k+n-1)/(2*n))); if (real(thepoles(k)) >= 0) thepoles(k) = 0; end end hh = find(thepoles); stpoles = thepoles(hh); % Stable Butterworth Poles % Getting Chebyshev Poles restpoles = real(stpoles); imstpoles = imag(stpoles);

else

restpoles = siv * restpoles; imstpoles = cov * imstpoles; stpoles = restpoles + j * imstpoles;

fprintf('\n Sorry! You entered a wrong choice'); end den = poly(stpoles); den = real(den); H = tf(1,den) % Transfer function h = impulse(1,den,50); % Impulse Response s = step(1,den,50); % Step Response t = linspace(0,50,length(h)); figure plot(t,h) xlabel('Time') ylabel('Amplitude') title('Normalized Impulse Response') figure plot(t,s) xlabel('Time') ylabel('Amplitude') title('Normalized Step Response') realpoles = real(stpoles); imagpoles = imag(stpoles); figure plot(realpoles,imagpoles,'*') axis([-1 1 -1.5 1.5]) grid on xlabel('Sigma') ylabel('j * Omega') title('Poles of the filter in S-plane') clear

FIR filter design using windows [HAMMING WINDOW]

EXP 10

%DESIGN A DIGITAL FIR LOW PASS FILTER WITH THE FOLLOWING SPECIFICATIONS %WP=0.2PI %Rp=0.25dB %Ws=0.3PI %As=50dB %CHOOSE THE APPROPRIATE WINDOW FUCTION %DETERMINE THE IMPULSE RESPONSE AND PROVIDE A PLOT FOR FREQUENCY RESPONSE %OF THE DESIGNATED RESPONSE %USING HAMMING WINDOW wp=0.2*pi; ws=0.3*pi; tr_width=ws-wp; M=ceil(6.6*pi/tr_width)+1; n=[0:1:M-1]; wc=(ws+wp)/2; %IDEAL LPF CUTOFF FREQUENCY alpha=(M-1)/2; m=n-alpha+eps; hd=sin(wc*m)./(pi*m); w_ham=(hamming(M)); h=hd' .* w_ham; [H,w]=freqz(h,1,1000,'whole'); H=(H(1:1:501))'; w=(w(1:1:501))'; mag=abs(H); db=20*log10((mag+eps)/max(mag)); pha=angle(H); grd=grpdelay(h,1,w); delta_w=2*pi/1000; Rp=-(min(db(1:1:wp/delta_w+1))); %ACTUAL PASS BAND RIPPLE As=-round(max(db(ws/delta_w+1:1:501))); %MIN STOP BAND ATTENUATION %PLOTS subplot(1,1,1); subplot(2,2,1);stem(n,hd);title('Ideal Impulse Response');axis([0 M-1 -0.1 0.3]);xlabel('n');ylabel('hd(n)'); subplot(2,2,2);stem(n,w_ham);title('HAMMING WINDOW');axis([0 M-1 0 1.1]);xlabel('n');ylabel('w(n)'); subplot(2,2,3);stem(n,h);title('Actual Impulse Response');axis([0 M-1 -0.1 0.3]);xlabel('n');ylabel('h(n)'); subplot(2,2,4);plot(w/pi,db);title('Magnitude Response');axis([0 1 -100 10]);xlabel('Frequency in pi units');ylabel('Decibles');

Butterworth digital IIR filter design [impulse invariant method]


%DESIGN A LOW PASS DIGITAL FILTER USING A ANALOG BUTTERWORTH PROTOTYPE TO %SATISFY Wp=0.2PI Rp=1dB Ws=0.3PI As=15dB %DIGITAL FILTER SPCIFICATIONS wp=0.2*pi; ws=0.3*pi; Rp=1; As=15; %DIGITAL PASSBAND FREQ IN RAD %DIGITAL STOPBAND FREQ IN RAD %PASSBAND RIPPLE IN DB %STOPBAND ATTENUATION IN DB

EXP 11

%ANALOG PROTOTYPE SPECIFICATION :INVERSE MAPPING FOR FREQUENCIES T=1; Omegap=wp/T; Omegas=ws/T; %SET T=1 %PROTOTYPE PASSBAND FREQUENCY %PROTOTYPE STOPBAND FREQUENCY

%ANALOG BUTTERWORTH PROTOTYPE FILTER CALCULATION [N, Wn] = BUTTORD(wp, ws, Rp, As); %BUTTERWORTH FILTER ORDER [b,a] = butter(N,Wn,'S'); [bz,az] = impinvar(b,a,10); [Ha,Wa] = freqs(b,a,512); [Hz,Wz] = freqz(bz,az,512,10); %PLOTS subplot(1,1,1); subplot(2,2,1);plot(Wa/(2*pi),20*log10(abs(Ha)));hold on;plot(Wz,20*log10(abs(Hz)));title('Magnitude Response');xlabel('|H|');ylabel('frequency'); %plot(Wa/(2*pi),20*log10(abs(Ha))); hold on; %plot(Wz,20*log10(abs(Hz)))

S-ar putea să vă placă și