0% found this document useful (0 votes)
45 views57 pages

Problem 2.1:: Frequency (HZ) Amplitude Spectrum (DFT)

Uploaded by

Farhad Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views57 pages

Problem 2.1:: Frequency (HZ) Amplitude Spectrum (DFT)

Uploaded by

Farhad Hossain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 57

Problem 2.

1:

close all;
clear all;

% Generate the sine wave sequence


fs = 8000; % Sampling rate
N = 1000; % Number of data points
t = (0:N-1) / fs; % Time vector
x = 2 * sin(2000 * pi * t);

% Apply the DFT algorithm


figure;
subplot(2,1,1);
xf = abs(fft(x)) / N; % Compute the amplitude spectrum
P = xf .* xf; % Compute the power spectrum
f = (0:N-1) * fs / N; % Map the frequency bin to the frequency (Hz)
plot(f, xf);
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (DFT)');

subplot(2,1,2);
plot(f, P);
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (DFT)');

% Convert it to one-sided spectrum


xf(2:N) = 2 * xf(2:N); % Get the single-sided spectrum
P = xf .* xf; % Calculate the power spectrum
f = (0:N/2) * fs / N; % Frequencies up to the folding frequency

figure;
subplot(2,1,1);
plot(f, xf(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (DFT)');

subplot(2,1,2);
plot(f, P(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (DFT)');
% Zero padding to the length of 1024
x = [x, zeros(1, 24)];
N = length(x);
xf = abs(fft(x)) / N; % Compute the amplitude spectrum with zero padding
P = xf .* xf; % Compute the power spectrum
f = (0:N-1) * fs / N; % Map frequency bin to frequency (Hz)

figure;
subplot(2,1,1);
plot(f, xf);
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (FFT)');

subplot(2,1,2);
plot(f, P);
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (FFT)');

% Convert it to one-sided spectrum


xf(2:N) = 2 * xf(2:N);
P = xf .* xf;
f = (0:N/2) * fs / N;

figure;
subplot(2,1,1);
plot(f, xf(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (FFT)');

subplot(2,1,2);
plot(f, P(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (FFT)');
Problem 2.3:

% Main script to demonstrate the biquant function

% Define parameters
NoBits = 3; % Number of bits used in quantization
Xmin = -5; % Minimum value of the input signal range
Xmax = 5; % Maximum value of the input signal range
value = 2.7; % Input value to be quantized

% Call the biquant function


[I, pq] = biquant(NoBits, Xmin, Xmax, value);

% Display results
disp(['Input value: ', num2str(value)]);
disp(['Quantization index (I): ', num2str(I)]);
disp(['Quantized value (pq): ', num2str(pq)]);

function [ I, pq] = biquant(NoBits, Xmin, Xmax, value)


% function pq ¼ biquant(NoBits, Xmin, Xmax, value)
% This routine is created for simulation of the uniform quantizer.
%
% NoBits: number of bits used in quantization.
% Xmax: overload value.
% Xmin: minimum value
% value: input to be quantized.
% pq: output of the quantized value
% I: coded integer index
L = 2^NoBits;
delta=(Xmax-Xmin)/L;
I=round((value-Xmin)/delta);
if ( I==L)
I=I-1;
end
if I <0
I = 0;
end
pq=Xmin+I*delta;
end

%%Input value: 2.7


%%Quantization index (I): 6
%%Quantized value (pq): 2.5

Problem 4.1:

% Example 4.8

close all;
clear all;

% Generate the sine wave sequence


fs = 8000; % Sampling rate
N = 1000; % Number of data points
t = (0:N-1) / fs; % Time vector
x = 2 * sin(2000 * pi * t);

% Apply the DFT algorithm


figure;
subplot(2,1,1);
xf = abs(fft(x)) / N; % Compute the amplitude spectrum
P = xf .* xf; % Compute the power spectrum
f = (0:N-1) * fs / N; % Map the frequency bin to the frequency (Hz)
plot(f, xf);
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (DFT)');

subplot(2,1,2);
plot(f, P);
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (DFT)');

% Convert it to one-sided spectrum


xf(2:N) = 2 * xf(2:N); % Get the single-sided spectrum
P = xf .* xf; % Calculate the power spectrum
f = (0:N/2) * fs / N; % Frequencies up to the folding frequency

figure;
subplot(2,1,1);
plot(f, xf(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (DFT)');
subplot(2,1,2);
plot(f, P(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (DFT)');

% Zero padding to the length of 1024


x = [x, zeros(1, 24)];
N = length(x);
xf = abs(fft(x)) / N; % Compute the amplitude spectrum with zero padding
P = xf .* xf; % Compute the power spectrum
f = (0:N-1) * fs / N; % Map frequency bin to frequency (Hz)

figure;
subplot(2,1,1);
plot(f, xf);
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (FFT)');

subplot(2,1,2);
plot(f, P);
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (FFT)');

% Convert it to one-sided spectrum


xf(2:N) = 2 * xf(2:N);
P = xf .* xf;
f = (0:N/2) * fs / N;

figure;
subplot(2,1,1);
plot(f, xf(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Amplitude spectrum (FFT)');

subplot(2,1,2);
plot(f, P(1:N/2 + 1));
grid on;
xlabel('Frequency (Hz)');
ylabel('Power spectrum (FFT)');
Problem 6.1:

% Nonzero initial conditions:


% y(-2) = 1, y(-1) = 0, x(-1) = -1, and x(n) = (0.8)^n * u(n)

y = zeros(1, 22); % Set up a vector to store y(n)


y(1:2) = [1, 0]; % Set initial conditions of y(-2) and y(-1)
n = 0:19; % Compute time indexes
x = (0.8).^n .* (n >= 0); % Compute 20 input samples of x(n)
x = [0, -1, x]; % Set initial conditions of x(-2) = 0 and x(-
1) = -1

for i = 1:20
y(i + 2) = 2 * x(i + 2) - 4 * x(i + 1) - 0.5 * y(i + 1) + 0.5 * y(i);
% Compute 20 outputs
end

% Display the results for nonzero initial conditions


figure;
subplot(3,1,1);
stem(n, x(3:22));
grid on;
xlabel('Sample number');
ylabel('Input x(n)');

subplot(3,1,2);
stem(n, y(3:22));
grid on;
xlabel('Number of samples, n (Nonzero initial conditions)');
ylabel('Output y(n)');
disp('Output y(n) with nonzero initial conditions:');
disp(y(3:22));

% Zero initial conditions:


% y(-2) = 0, y(-1) = 0, x(-1) = 0, and x(n) = 1 / (n + 1)

y = zeros(1, 22); % Set up a vector to store y(n)


n = 0:19; % Compute time indexes
x = 1 ./ (n + 1); % Compute 20 input samples of x(n)
x = [0, 0, x]; % Set zero initial conditions of x(-2) = 0 and
x(-1) = 0
for i = 1:20
y(i + 2) = 2 * x(i + 2) - 4 * x(i + 1) - 0.5 * y(i + 1) + 0.5 * y(i);
% Compute 20 outputs
end

% Display the results for zero initial conditions


subplot(3,1,3);
stem(n, y(3:22));
grid on;
xlabel('Number of samples, n (Zero initial conditions)');
ylabel('Output y(n)');
disp('Output y(n) with zero initial conditions:');
disp(y(3:22));

Problem 6.2:

% Example 6.12

% Plot the magnitude frequency response and phase response


% Case a
figure(1)
h = freqz([1, 1, -0.5], 1, 1024); % Calculate the frequency response
w = linspace(0, pi, 1024);
phi = 180 * unwrap(angle(h)) / pi;
subplot(2, 1, 1), plot(w, abs(h)), grid on, xlabel('Frequency (radians)'),
ylabel('Magnitude')
subplot(2, 1, 2), plot(w, phi), grid on, xlabel('Frequency (radians)'),
ylabel('Phase (degrees)')
title('Case a')

% Case b
figure(2)
h = freqz([1, -0.5, 1], 1, 1024); % Calculate the frequency response
phi = 180 * unwrap(angle(h)) / pi;
subplot(2, 1, 1), plot(w, abs(h)), grid on, xlabel('Frequency (radians)'),
ylabel('Magnitude')
subplot(2, 1, 2), plot(w, phi), grid on, xlabel('Frequency (radians)'),
ylabel('Phase (degrees)')
title('Case b')

% Case c
figure(3)
h = freqz([0.5, -0.32], [1, -0.5, 0.25], 1024); % Calculate the frequency
response
phi = 180 * unwrap(angle(h)) / pi;
subplot(2, 1, 1), plot(w, abs(h)), grid on, xlabel('Frequency (radians)'),
ylabel('Magnitude')
subplot(2, 1, 2), plot(w, phi), grid on, xlabel('Frequency (radians)'),
ylabel('Phase (degrees)')
title('Case c')

% Case d
figure(4)
h = freqz([1, -0.9, 0.81], [1, -0.6, 0.36], 1024); % Calculate the
frequency response
phi = 180 * unwrap(angle(h)) / pi;
subplot(2, 1, 1), plot(w, abs(h)), grid on, xlabel('Frequency (radians)'),
ylabel('Magnitude')
subplot(2, 1, 2), plot(w, phi), grid on, xlabel('Frequency (radians)'),
ylabel('Phase (degrees)')
title('Case d')
Problem 6.3:

% Matlab program for Figures 6.30 and 6.31

close all;
clear all;
fs = 8000; % Sampling rate
alpha = 0:9; % Degree of pre-emphasis
figure(1);
freqz([1-alpha],1,512,fs); % Calculate and display frequency responses
load speech.dat
figure(2);
y = filter([1-alpha],1,speech); % Filtering speech
subplot(2,1,1), plot(speech, 'k'), grid on;
ylabel("Speech samples");
title("Speech: We lost the golden chain.")
subplot(2,1,2), plot(y, 'k'), grid on;
ylabel("Filtered samples");
xlabel("Number of samples");
title("Pre-emphasized speech.");
figure(3);
N = length(speech); % Length of speech
Axk = abs(fft(speech.*hamming(N)'))/N; % Two-sided spectrum of speech
Ayk = abs(fft(y.*hamming(N)'))/N; % Two-sided spectrum of pre-emphasized
speech
f = [0:N/2]*fs/N;
Axk(2:N/2+1) = 2*Axk(2:N/2+1); % Get one-sided spectrum of speech
Ayk(2:N/2+1) = 2*Ayk(2:N/2+1); % Get one-sided spectrum of filtered speech
subplot(2,1,1), plot(f, Axk(1:N/2+1), 'k'), grid on;
ylabel('Amplitude spectrum Ak')
title('Original speech');
subplot(2,1,2), plot(f, Ayk(1:N/2+1), 'k'), grid on;
ylabel('Amplitude spectrum Ak')
xlabel('Frequency (Hz)');
title('Preemphasized speech');
Problem 7.1:

% MATLAB program to plot frequency responses

[hz, w] = freqz([-0:09355 -0:015580:1 -0:01558 -0:09355], [1], 512);


phi= 180*unwrap(angle(hz))/pi;
subplot(2,1,1), plot(w,20*log10(abs(hz))),grid;
xlabel("Frequency (radians)");
ylabel("Magnitude Response (dB)")
subplot(2,1,2), plot(w, phi);grid;
xlabel("Frequency (radians)");
ylabel("Phase (degrees)");
Problem 7.3:

N = 25;
fs = 8000;
% Design using the rectangular window
Ftype = 1; WnL = 0.2; WnH = 0; Wtype = 1;
Brec = fir1(N, WnL, 'low', rectwin(N+1));
% Design using the Hamming window
Ftype = 1; WnL = 0.2; WnH = 0; Wtype = 4;
Bham = fir1(N, WnL, 'low', hamming(N+1));

[hrec, f] = freqz(Brec, 1, 512, fs);


[hham, f] = freqz(Bham, 1, 512, fs);
prec = 180 * unwrap(angle(hrec)) / pi;
pham = 180 * unwrap(angle(hham)) / pi;

subplot(2,1,1);
plot(f, 20*log10(abs(hrec)), '-', f, 20*log10(abs(hham))); grid on;
axis([0 4000 -100 10]);
xlabel("Frequency (Hz)"); ylabel("Magnitude Response (dB)");
subplot(2,1,2);
plot(f, prec, '-', f, pham); grid on;
xlabel("Frequency (Hz)"); ylabel("Phase (degrees)");
Problem 7.5:

clc;
clf;
close all;
clear all;
% Filter specifications
Fs = 8000; % Sampling rate
Fstop1 = 500; % Lower stopband frequency (Hz)
Fpass1 = 1600; % Lower passband frequency (Hz)
Fpass2 = 2300; % Upper passband frequency (Hz)
Fstop2 = 3500; % Upper stopband frequency (Hz)
Astop = 50; % Stopband attenuation (dB)
Apass = 0.05; % Passband ripple (dB)

% Normalize frequencies
Fnorm = [Fstop1 Fpass1 Fpass2 Fstop2] / (Fs/2);

% Design the filter using the FIRPM function


b = firpm(50, Fnorm, [0 0 1 1], [10^(Astop/20) 10^(Apass/20)],
'bandpass');

% Frequency response of the designed filter


freqz(b, 1, 1024, Fs);

% Plot the magnitude response


title('Magnitude Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

Problem 7.8:
% Define parameters

fs = 1000; % Sampling frequency (Hz)


f_signal = 50; % Signal frequency (Hz)
T = 1; % Duration of signal (s)
t = 0:1/fs:T-1/fs; % Time vector

% Generate a noisy sine wave signal


x_clean = sin(2*pi*f_signal*t); % Clean signal
noise = 0.5*randn(size(t)); % Gaussian white noise
x_noisy = x_clean + noise; % Noisy signal
% Apply noise filtering (Moving average filter)
window_size = 10; % Window size for moving average
b = (1/window_size)*ones(1,window_size);% Filter coefficients

% Apply the filter


x_filtered = filter(b, 1, x_noisy); % Apply moving average filter

% Plot original noisy signal and filtered signal


figure;
subplot(2,1,1);
plot(t, x_noisy);
title('Noisy Signal');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

subplot(2,1,2);
plot(t, x_filtered);
title('Filtered Signal');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;
Problem 7.9:

clc;
clf;
close all;
clear all;
% Filter specifications
Fs = 8000; % Sampling rate
Fstop1 = 500; % Lower stopband frequency (Hz)
Fpass1 = 1600; % Lower passband frequency (Hz)
Fpass2 = 2300; % Upper passband frequency (Hz)
Fstop2 = 3500; % Upper stopband frequency (Hz)
Astop = 50; % Stopband attenuation (dB)
Apass = 0.05; % Passband ripple (dB)

% Normalize frequencies
Fnorm = [Fstop1 Fpass1 Fpass2 Fstop2] / (Fs/2);

% Design the filter using the FIRPM function


b = firpm(50, Fnorm, [0 0 1 1], [10^(Astop/20) 10^(Apass/20)],
'bandpass');

% Frequency response of the designed filter


freqz(b, 1, 1024, Fs);

% Plot the magnitude response


title('Magnitude Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;
Problem 7.10:

clc;

clf;

close all;
clear all;

fs = 8000; % Sampling rate


passband = [0 800]; % Passband frequencies in Hz
stopband = [1000 4000]; % Stopband frequencies in Hz
passband_ripple = 1; % Passband ripple in dB
stopband_attenuation = 40; % Stopband attenuation in dB
filter_order = 53; % Filter order

% Calculate normalized frequencies


norm_passband = passband / (fs/2);
norm_stopband = stopband / (fs/2);

% Ideal frequency response


ideal_response = [1 1 0 0];
% Weight factors for passband ripple and stopband attenuation
w = [1 1];

% Design the filter using the Parks-McClellan algorithm


try
b = remez(filter_order, [0 norm_passband(2) norm_stopband(1) 1],
ideal_response, w);

% Plot frequency response


freqz(b, 1, 512, fs);
title('Lowpass Filter Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

catch ME
disp(ME.message);
end
Problem 7.11:

clc;

clf;
close all;
clear all;

fs = 8000; % Sampling rate


passband = [1000 1600]; % Passband frequencies in Hz
stopband = [0 600 2000 4000]; % Stopband frequencies in Hz
passband_ripple = 1; % Passband ripple in dB
stopband_attenuation = 30; % Stopband attenuation in dB
filter_order = 25; % Filter order

% Calculate normalized frequencies


norm_passband = passband / (fs/2);
norm_stopband = stopband / (fs/2);

% Ideal frequency response


ideal_response = [0 0 1 1 0 0];

% Weight factors for passband ripple and stopband attenuation


w = [1 30 1];

% Design the filter using the Parks-McClellan algorithm


try
b = remez(filter_order, [0 norm_passband(1)-0.01 norm_passband(1)
norm_passband(2) norm_passband(2)+0.01 1], ideal_response, w);

% Plot frequency response


freqz(b, 1, 512, fs);
title('Frequency Response');
axis([0 fs/2 -80 10]);
grid on;

catch ME
disp(ME.message);
end
Problem 7.12:

clc;

clf;
close all;
clear all;

sample = 1:10; % Input test array


x = zeros(1, length(sample) + 2); % Initialize input buffer with
sufficient length
y = zeros(size(sample)); % Initialize output buffer
b = [1, 0, 1, 2, 0, 36]; % FIR filter coefficients [b0 b1...]

KK = length(b);

for n = 1:length(sample) % Loop processing


for k = KK:-1:2 % Shift the input by one sample
x(k) = x(k - 1);
end
x(1) = sample(n); % Get new sample
y(n) = 0; % Perform FIR filtering
for k = 1:KK
y(n) = y(n) + b(k)*x(k);
end
end

out = y; % Output is stored in 'out'

% Display output
disp('Filtered Output:');
disp(out);

% Plot output
figure;
subplot(2, 1, 1);
stem(sample, out, 'filled');
xlabel('Sample');
ylabel('Output');
title('Filtered Output');
grid on;

subplot(2, 1, 2);
stem(b, 'filled');
xlabel('Coefficient Index');
ylabel('Coefficient Value');
title('FIR Filter Coefficients');
grid on;
Problem 7.13:

clc;
clf;
close all;
clear all;
% Define filter specifications
Fs = 8000; % Sampling frequency (Hz)
Fpass = 100; % Passband frequency (Hz)
Fstop = 150; % Stopband frequency (Hz)
Apass = 0.5; % Passband ripple (dB)
Astop = 40; % Stopband attenuation (dB)

% Design the filter


N = 25; % Filter order (number of taps)
b = fir1(N, Fpass/(Fs/2), 'low', hamming(N+1));

% Scale and quantize filter coefficients


scale_factor = 2^7; % Scale factor
quantized_b = round(b * scale_factor); % Quantize coefficients

% Display original and quantized coefficients


disp('Original coefficients:');
disp(b);
disp('Quantized coefficients:');
disp(quantized_b);

% Plot frequency response of original filter


freqz(b, 1, 1024, Fs);

% Plot frequency response of quantized filter


hold on;
freqz(quantized_b/scale_factor, 1, 1024, Fs);
legend('Original Filter', 'Quantized Filter');
title('Frequency Response');

Problem 7.14:

clc;

clf;
close all;
clear all;
f1=100;f2=200;%the frequencies of sines signal that needs filtered
fs=2000;%sampling frequency
m=(0.3*f1)/(fs/2);%define tansition bandwidth
M=round(8/m);%define the window length
N=M-1;%define the order of filter
b=fir1(N,0.5*f2/(fs/2));%use the firl function to design a filter
%Input parameters are respectively the order number and the cutoff
%frequency of filter
figure(1)
[h,f]=freqz(b,1,512);%amplitude-frequency characteristic graph
plot(f*fs/(2*pi),20*log10(abs(h)))%parameters are respectively frequency and
amplitude
xlabel('frequency/Hz');ylabel('gain/dB');title('The gain response of lowpass
filter');
figure(2)
subplot(211)
t=0:1/fs:0.2;%define the time domain and the steplength
s=sin(2*pi*f1*t)+sin(2*pi*f2*t);%signal before filtering
plot(t,s);%plot the signal graph before filtering
xlabel('time/s');ylabel('amplitude');title('Time-domain diagram before
filtering');
axis([0 0.1 -2 2]);
subplot(212)
Fs=fft(s,512);%transform the signal to frequency domain
AFs=abs(Fs);%take the amplitude
f=(0:255)*fs/512;%frequency sampling
plot(f,AFs(1:256));%plot the frequency domain diagram before filtering
xlabel('frequency/Hz');ylabel('amplitude');title('Frequency-domain diagram before
filtering');
figure(3)
sf=filter(b,1,s);%use filter function to filter
subplot(211)
plot(t,sf)%plot the signal graph after filtering
xlabel('time/s');ylabel('amplitude');title('Time-domain diagram after
filtering');
axis([0.1 0.2 -2 2]);
subplot(212)
Fsf=fft(sf,512);%frequency-domain diagram after filtering
AFsf=abs(Fsf);%the amplitude
f=(0:255)*fs/512;%frequency sampling
plot(f,AFsf(1:256))%plot the frequency domain diagram after filtering
xlabel('frequency/Hz');ylabel('amplitude');title('Frequency-domain diagram
after filtering');
Problem 7.15:

clc;
clf;
close all;
clear all;
M=32;%the number of samples
Wp=0.6*pi;%passband cutoff frequency
m=0:M/2;%the sampling points
Wm=2*pi*m./(M+1);%stopband cutoff frequency
mtr=ceil(Wp*(M+1)/(2*pi));%round to positive part,i.e.ceil(3.5)=4;ceil(-
3.2)=-3;
Ad=[Wm>=Wp];
Ad(mtr)=0.28;
Hd=Ad.*exp(-j*0.5*M*Wm);%define frequency-domain sampling vector H(k))
Hd=[Hd conj(fliplr(Hd(2:M/2+1)))];
%fliplr is to realize the fliplr of matrix and conj is the conjugate
h=real(ifft(Hd));%h(n)=IDFT[H(k)]
w=linspace(0,pi,1000);%get 1000 row vectors between 0 and pi
H=freqz(h,[1],w);%the amplitude -frequency characteristic diagram of the
filter
figure(1)
plot(w/pi,20*log10(abs(H)));%parameters are respectively the normalized
frequency and amplitude
xlabel('the normailzed frequency');ylabel('gian/dB');title('The gain
response of highpass filter');
axis([0 1 -50 0]);
f1=200;f2=700;f3=800;%the frequencies of sines signal that needs filtered
fs=2000;%the sample frequency
figure(2)
subplot(211)
t=0:1/fs:0.25;%define the time domain and steplength
s=sin(2*pi*f1*t)+sin(2*pi*f2*t)+sin(2*pi*f3*t);%signal before filtering
plot(t,s);%plot the diagram before filtering
xlabel('time/s');ylabel('amplitude');title('Time-domain diagram before
filtering');
subplot(212)
Fs=fft(s,512);%transform to the frequency domain
AFs=abs(Fs);%the amplitude
f=(0:255)*fs/512;%frequency sampling
plot(f,AFs(1:256));%plot the frequency domain diagram before filtering
xlabel('frequency/Hz');ylabel('amplitude');title('Frequency-domain diagram
before filtering');
figure(3)
sf=filter(h,1,s);%use function filter
subplot(2,1,1)
plot(t,sf)%plot the diagram after filtering
xlabel('time/s');ylabel('amplitude');title('Time-domain diagram after
filtering')
axis([0.2 0.25 -2 2]); %set the range of image coordinates
subplot(2,1,2)
Fsf=fft(sf,512);AFsf=abs(Fsf);
f=(0:255)*fs/512;%frequency sampling
plot(f,AFsf(1:256))%plot the frequency domain diagram before filtering
xlabel('frequency/Hz');ylabel('amplitude');title('Frequency-domain diagram
after filtering');
Problem 8.1:

clc;

clf;
close all;
clear all;

syms s

% Define the lowpass prototype transfer function


LP_prototype = 1 / (s + 1);

% Highpass filter transfer function


HP_cutoff = 40; % Cutoff frequency for highpass filter (radians per
second)
HP = LP_prototype * (s / HP_cutoff);
HP_mag = simplify(abs(HP));

% Bandpass filter transfer function


BP_center = 100; % Center frequency for bandpass filter (radians per
second)
BP_bandwidth = 20; % Bandwidth for bandpass filter (radians per second)
BP = LP_prototype * ((s^2 + BP_center^2) / (s^2 + BP_bandwidth*BP_center*s
+ BP_center^2));
BP_mag = simplify(abs(BP));

% Define the frequency range for plotting


w = linspace(0, 200, 1000); % Frequency range from 0 to 200 radians per
second

% Evaluate magnitude responses for highpass and bandpass filters


HP_mag_eval = double(subs(HP_mag, s, 1j*w));
BP_mag_eval = double(subs(BP_mag, s, 1j*w));

% Plot magnitude responses using subplots


figure;

% Plot magnitude response of the highpass filter


subplot(2, 1, 1);
plot(w, HP_mag_eval, 'b', 'LineWidth', 2);
xlabel('Frequency (radians per second)');
ylabel('Absolute filter gain');
title('Magnitude Response of Highpass Filter (40 rad/s cutoff)');
grid on;

% Plot magnitude response of the bandpass filter


subplot(2, 1, 2);
plot(w, BP_mag_eval, 'r', 'LineWidth', 2);
xlabel('Frequency (radians per second)');
ylabel('Absolute filter gain');
title('Magnitude Response of Bandpass Filter (100 rad/s center, 20 rad/s
bandwidth)');
grid on;
Problem 8.2:

% Plot the magnitude and phase responses


% Sampling rate (Hz)
fs = 90;

% Designing an analog lowpass filter with cutoff frequency 103.92 rad/s


[B, A] = lp2lp([1], [1 1], 103.92);

% Converting the analog filter to a digital filter using the bilinear


transformation
[b, a] = bilinear(B, A, fs);

% Compute the frequency response of the digital filter


[hz, f] = freqz([0.3660 0.3660], [1 -0.2679], 512, fs);

% Unwrap the phase response


phi = 180 * unwrap(angle(hz)) / pi;

% Plotting the magnitude response


subplot(2,1,1)
plot(f, abs(hz)), grid;
axis([0 fs/2 0 1]);
xlabel('Frequency (Hz)'); ylabel('Magnitude Response');

% Plotting the phase response


subplot(2,1,2)
plot(f, phi); grid;
axis([0 fs/2 -100 0]);
xlabel('Frequency (Hz)'); ylabel('Phase (degrees)');

Problem 8.3:

%(Digital Butterworth and Chebyshev Filter Designs)

%Program 8.3. MATLAB program for Example 8.7.

% Example 8.7: Design of the digital lowpass Butterworth filter


% Given parameters
format long
fs = 8000; % Sampling rate

% Step 2: Design the analog lowpass Butterworth filter


[B, A] = lp2lp([1], [1 1], 1.0691 * 10^4);
% Step 3: Convert the analog filter to a digital filter using the bilinear
%transformation
[b, a] = bilinear(B, A, fs);

% Plot the magnitude and phase responses


freqz(b, a, 512, fs);
axis([0 fs/2 -20 1]); % Setting the axis limits

Problem 8.4:
% Design of the digital highpass Butterworth filter

format long;
fs = 8000; % Sampling rate
[B, A] = lp2hp([1.9652],[1, 1.9652], 3.8627*10^4); % Complete step 2
[b, a] = bilinear(B, A, fs); % Complete step 3

% Plot the magnitude and phase responses


% b = [0.4487 -0.4487]; % numerator coefficients from MATLAB
% a = [1 0.1025]; % denominator coefficients from MATLAB
freqz(b, a, 512, fs);
axis([0 fs/2 -40 2]);
Problem 8.5:

Design of the digital lowpass Butterworth filter


format long;
fs = 8000; % Sampling rate
[B, A] = lp2lp([1],[1 1.4142 1], 6.6645*10^4); % Complete step 2
[b, a] = bilinear(B, A, fs); % Complete step 3

% Plot the magnitude and phase responses


% b = [0.7157 1.4315 0.7157]; % numerator coefficients from MATLAB
% a = [1 1.3490 0.5140]; % denominator coefficients from MATLAB
freqz(b, a, 512, fs);
axis([0 fs/2 -40 10]);

Problem 8.6:

% Design of the digital lowpass Chebyshev filter

format long;
fs = 8000; % Sampling rate
% Lowpass to Highpass Transformation
[B, A] = lp2hp([1.4314], [1, 1.4256, 1.5162], 3.8627 * 10 ^ 4);

% Bilinear Transformation
[b, a] = bilinear(B, A, fs);

% Plot the magnitude and phase responses


b = [0.1327, -0.2654, 0.1327]; % Corrected numerator coefficients
a = [1, 0.7996, 0.3618]; % Corrected denominator coefficients
freqz(b, a, 512, fs);
axis([0, fs/2, -40, 10]); % Corrected axis limits

Problem 8.7:

% Design of the digital bandpass Butterworth filter

format long
fs = 8000;
[B,A] = lp2bp([1],[1 1],sqrt(5.7499* 10 ^ 8),4088) ; % Complete step 2
[b,a] = bilinear(B,A,fs) % Complete step 3
% Plot the magnitude and phase responses
b = [0.0730, -0.0730]; %numerator coefficients from MATLAB
a =[1, 0.7117, 0.8541]; %denominator coefficients from MATLAB
freqz(b, a,512,fs);
axis([0, fs/2, -40, 10]);

Problem 8.8:

% Design of the digital bandstop Butterworth filter

format long
fs = 8000; % Sampling rate
[B, A] = lp2bs([1],[1 1],sqrt(5.7341*10^8),4149)% Complete step 2
[b, a] = bilinear(B,A,fs)% Complete step 3
% Plot the magnitude and phase responses
b = [0.9259 0.7078 0.9259]; %numerator coefficients from MATLAB
a = [1 0.7078 0.8518]; %denominator coefficients from MATLAB
freqz(b,a,512,fs);
axis([0 fs/2 -40 10])
Problem 8.9:

% Design of the digital bandpass Chebyshev filter

format long
fs = 8000;
[B, A] = lp2bp([2.8628],[1 2.8628],sqrt(5.7341*10^8),4016) % Complete
step 2
[b, a] = bilinear(B,A,fs) % Complete step 3
% Plot the magnitude and phase responses
b = [0.1815 0.0 -0.1815]; %numerator coefficients from MATLAB
a = [1 0.6264 0.6369]; %denominator coefficients from MATLAB
freqz(b,a,512,fs);
axis([0 fs/2 -40 10])
Problem 8.10:

% Design of the fourth-order digital lowpass Butterworth filter

% in the cascade form


format long
fs = 8000; % Sampling rate
[B1, A1] = lp2lp([1],[1 0.7654 1], 2.3946*10^4)% Complete step 2
[b1, a1] = bilinear(B1,A1,fs)% Complete step 3
[B2, A2] = lp2lp([1],[1 1.8478 1], 2.3946*10^4)% Complete step 2
[b2, a2] = bilinear(B2,A2,fs)% Complete step 3
% Plot the magnitude and phase responses
b1 = [0.5108 1.0215 0.5108];
a1 = [1 0.5654 0.4776]; % from MATLAB
b2 = [0.3730 0.7460 0.3730];
a2 = [1 0.4129 0.0790]; %coefficients from MATLAB
freqz(conv(b1,b2),conv(a1,a2),512,fs);% Combined filter responses
axis([0 fs/2 -40 10]);
Problem 8.11:

close all;

clear all;

% Filter coefficients (Butterworth type designed using the BLT)


B0 = [0.00319549340 0.0031954934];
A0 = [1.0000000000 -1.9934066716 0.9936090132];
B1 = [0.00637081020 0.0063708102];
A1 = [1.0000000000 -1.9864516324 0.9872583796];
B2 = [0.0126623878 0 -0.0126623878];
A2 = [1.0000000000 -1.9714693192 0.9746752244];
B3 = [0.03109004130 0.0310900413];
A3 = [1.0000000000 -1.9181849043 0.9378199174];
B4 = [0.0746111954 0 -0.0746111954];
A4 = [1.0000000000 -1.7346085867 0.8507776092];
B5 = [0.1663862883 0 -0.1663862884];
A5 = [1.0000000000 -1.0942477187 0.6672274233];
B6 = [0.3354404899 0 -0.3354404899];
A6 = [1.0000000000 -0.7131366534 0.3291190202];

[h0, f] = freqz(B0, A0, 2048, 44100);


[h1, f] = freqz(B1, A1, 2048, 44100);
[h2, f] = freqz(B2, A2, 2048, 44100);
[h3, f] = freqz(B3, A3, 2048, 44100);
[h4, f] = freqz(B4, A4, 2048, 44100);
[h5, f] = freqz(B5, A5, 2048, 44100);
[h6, f] = freqz(B6, A6, 2048, 44100);

loglog(f, abs(h0), f, abs(h1), f, abs(h2), ...


f, abs(h3), f, abs(h4), f, abs(h5), f, abs(h6));
xlabel('Frequency (Hz)');
ylabel('Filter Gain');
grid on;
axis([10 10^5 10^(-6) 1]);

figure(2);

g0 = 10;
g1 = 10;
g2 = 0;
g3 = 0;
g4 = 0;
g5 = 10;
g6 = 10;

p0 = 0;
p1 = pi/14;
p2 = 2 * p1;
p3 = 3 * p1;
p4 = 4 * p1;
p5 = 5 * p1;
p6 = 6 * p1;

n = 0:1:20480; % Indices of samples


fs = 44100; % Sampling rate

x = sin(2 * pi * 100 * n / fs) + sin(2 * pi * 200 * n / fs + p1) + ...


sin(2 * pi * 400 * n / fs + p2) + sin(2 * pi * 1000 * n / fs + p3) +
...
sin(2 * pi * 2500 * n / fs + p4) + sin(2 * pi * 6000 * n / fs + p5) +
...
sin(2 * pi * 15000 * n / fs + p6); % Generate test audio signals

y0 = filter(B0, A0, x); % Bandpass filter 0


y1 = filter(B1, A1, x); % Bandpass filter 1
y2 = filter(B2, A2, x); % Bandpass filter 2
y3 = filter(B3, A3, x); % Bandpass filter 3
y4 = filter(B4, A4, x); % Bandpass filter 4
y5 = filter(B5, A5, x); % Bandpass filter 5
y6 = filter(B6, A6, x); % Bandpass filter 6

y = g0 .* y0 + g1 .* y1 + g2 .* y2 + g3 .* y3 + g4 .* y4 + g5 .* y5 + g6
.* y6 + x; % Equalizer output

N = length(x);
Axk = 2 * abs(fft(x)) / N;
Axk(1) = Axk(1) / 2; % One-sided amplitude spectrum of the input
f = [0:N/2] * fs / N;

subplot(2,1,1);
loglog(f, Axk(1:N/2+1));
title('Audio spectrum');
axis([10 100000 0.00001 100]);
grid on;

Ayk = 2 * abs(fft(y)) / N;
Ayk(1) = Ayk(1) / 2; % One-sided amplitude spectrum of the output

subplot(2,1,2);
loglog(f, Ayk(1:N/2+1));
xlabel('Frequency (Hz)');
title('Equalized audio spectrum');
axis([10 100000 0.00001 100]);
grid on;
Problem 8.12:

%Example 8.15.

%Plot the magnitude responses |H(s)| and |H(z)| for the Laplace transfer function
H(s)
f = 0:0.1:5; % Frequency range and sampling interval
w = 2*pi*f; % Frequency range in rad/sec
hs = freqs([2],[1 2],w); % Analog frequency response
phis = 180*angle(hs)/pi;

% For the z-transfer function H(z)


hz = freqz([0.2],[1 -0.8187],length(w)); % Digital frequency response
hzscale = freqz([0.1813],[1 -0.8187],length(w)); % Scaled digital mag. response
phiz = 180*angle(hz)/pi;

% Plot magnitude and phase responses


subplot(3,1,1), plot(f,abs(hs),'kx',f,abs(hz),'k-'), grid on, axis([0 5 0 1.2]);
xlabel('Frequency (Hz)'), ylabel('Mag. Responses')
legend('|H(s)|', '|H(z)|')

subplot(3,1,2), plot(f,abs(hs),'kx',f,abs(hzscale),'k-'), grid on, axis([0 5 0


1.2]);
xlabel('Frequency (Hz)'), ylabel('Scaled Mag. Responses')
legend('|H(s)|', '|H(z)| scaled')

subplot(3,1,3), plot(f,phis,'kx',f,phiz,'k-'), grid on;


xlabel('Frequency (Hz)'), ylabel('Phases (deg.)');
legend('Phase of H(s)', 'Phase of H(z)')

Problem 8.13:
%Example 8.16
% Plot the magnitude responses jH(s)j and jH(z)j
% For the Laplace transfer function H(s)
f =0:0.1:5;
T =0.1; % Initialize analog frequency range in Hz and sampling interval
w =2*pi*f;
% Convert the frequency range to radians/second
hs =freqs([1 0],[1 2 5],w);
% Calculateanalogfilterfrequencyresponses
phis =180*angle(hs)/pi;
% For the z-transfer function H(z)
% Calculate digital filter frequency responses
hz =freqz([0.1 -0.09766],[1 -1.7735 0.8187],length(w));
phiz =180*angle(hz)/pi;
% Plot magnitude and phase responses
subplot(2,1,1), plot(f,abs(hs),'x',f, abs(hz),'-'),grid;
xlabel('Frequency (Hz)');ylabel('Magnitude Responses')
subplot(2,1,2), plot(f,phis, 'x',f, phiz,'-');grid;
xlabel('Frequency (Hz)');ylabel('Phases (degrees)')

Problem 8.14:

clc;

center_frequency = 1500; % Center frequency in Hz


bandwidth = 200; % Bandwidth in Hz
ripple = 0.5; % Ripple in dB
Fs = 8000; % Sampling frequency in Hz

Wp1 = (center_frequency - bandwidth/2) / (Fs/2);


Wp2 = (center_frequency + bandwidth/2) / (Fs/2);

[N, Wn] = cheb2ord([Wp1, Wp2], [Wp1 - 0.05, Wp2 + 0.05], ripple, 3);
[num, den] = cheby2(N, ripple, [Wp1, Wp2], 'bandpass');

disp('Transfer function:');
disp(['Numerator: ', num2str(num)]);
disp(['Denominator: ', num2str(den)]);
disp(' ');

freqz(num, den, 512, Fs);

title('Magnitude and Phase Response');


xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

Problem 8.15:

%8.15

clc;
center_frequency = 2500;
bandwidth = 200;
ripple = 1;
Fs = 8000;

Wp1 = (center_frequency - bandwidth/2) / (Fs/2);


Wp2 = (center_frequency + bandwidth/2) / (Fs/2);
[N, Wn] = cheb2ord([Wp1, Wp2], [Wp1 - 0.05, Wp2 + 0.05], ripple, 3); % Chebyshev
filter order estimation
[num, den] = cheby2(N, ripple, [Wp1, Wp2], 'stop');

disp('Transfer function:');
disp(['Numerator: ', num2str(num)]);
disp(['Denominator: ', num2str(den)]);
disp(' ');

freqz(num, den, 512, Fs);

title('Magnitude and Phase Response');


xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
grid on;

Problem 8.16:

clc;

% Define filter parameters


fs = 8000; % Sampling frequency (Hz)
fc = 2000; % Cutoff frequency (Hz)
Rp = 3; % Passband ripple (dB)

% Normalize cutoff frequency


Wn = fc / (fs/2);

% Design the filter


[b, a] = butter(4, Wn);

% Calculate the difference equation


a1 = a(2:end);
b1 = b(2:end);
diffeq = [b(1) a1];

% Plot frequency response


[h,f] = freqz(b, a, 512, fs);
mag = 20*log10(abs(h));
phase = rad2deg(angle(h));

% Plot magnitude response


figure(1);
subplot(2,1,1);
plot(f, mag);
grid on;
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('Magnitude Frequency Response');

% Plot phase response


subplot(2,1,2);
plot(f, phase);
grid on;
xlabel('Frequency (Hz)');
ylabel('Phase (degrees)');
title('Phase Frequency Response');
Problem 8.17:

clc;

fs = 8000;
fc = 1500;
Rp = 0.5;

Wn = fc / (fs/2);

[b, a] = cheby1(4, Rp, Wn);

a1 = a(2:end);
b1 = b(2:end);
diffeq = [b(1) a1];

[h,f] = freqz(b, a, 512, fs);


mag = 20*log10(abs(h));
phase = rad2deg(angle(h));

figure(1);
subplot(2,1,1);
plot(f, mag);
grid on;
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('Magnitude Frequency Response');

subplot(2,1,2);
plot(f, phase);
grid on;
xlabel('Frequency (Hz)');
ylabel('Phase (degrees)');
title('Phase Frequency Response');

Problem 8.18:

fs = 8000; % Sampling rate

t = 0: 1/fs:1; % Time vector for 1 second


x =zeros(1,length(t)); % Initialize input to be zero
x(1) = 1; % Set up impulse function
y = filter([0 0:707107],[1 1:414214 1],x); % Perform filtering
subplot(2,1,1);plot(t(1:400),y(1:400));grid
ylabel('y(n) 1 kHz tone');
xlabel('time (second)')
Ak =2*abs(fft(y))/length(y);Ak(1) = Ak(1)/2; % One-sided amplitude spectrum
f =(0:1:(length(y)- 1)/2)*fs/length(y); % Indices to frequencies (Hz) for plot
subplot(2,1,2);plot(f,Ak(1:(length(y)+1)/2));grid
ylabel('Spectrum for y(n)');
xlabel('frequency (Hz)')

Problem 8.19:

close all;
clear all;
fs = 8000;
t = 0:1/fs:1; x = zeros(1, length(t));
x(1) = 1;
y852 = filter([0 sin(2*pi*852/fs)], [1 -2*cos(2*pi*852/fs) 1], x);
y1209 = filter([0 sin(2*pi*1209/fs)], [1 -2*cos(2*pi*1209/fs) 1], x);
y7 = y852 + y1209;
subplot(2,1,1);
plot(t(1:400), y7(1:400));
grid on;
ylabel('y(n) DTMF: number 7');
xlabel('time (second)');
Ak = 2 * abs(fft(y7)) / length(y7);
Ak(1) = Ak(1) / 2;
f = [0:1:(length(y7) - 1)/2] * fs / length(y7);
subplot(2,1,2);
plot(f, Ak(1:(length(y7) + 1)/2));
grid on;
ylabel('Spectrum for y7(n)');
xlabel('frequency (Hz)');

Problem 8.20:

close all;
clear all;
N = 205;
fs = 8000;
t = [0:1:N-1]/fs;
x = zeros(1, length(t));
x(1) = 1;
y697 = filter([0 sin(2*pi*697/fs)], [1 -2*cos(2*pi*697/fs) 1], x);
y770 = filter([0 sin(2*pi*770/fs)], [1 -2*cos(2*pi*770/fs) 1], x);
y852 = filter([0 sin(2*pi*852/fs)], [1 -2*cos(2*pi*852/fs) 1], x);
y941 = filter([0 sin(2*pi*941/fs)], [1 -2*cos(2*pi*941/fs) 1], x);
y1209 = filter([0 sin(2*pi*1209/fs)], [1 -2*cos(2*pi*1209/fs) 1], x);
y1336 = filter([0 sin(2*pi*1336/fs)], [1 -2*cos(2*pi*1336/fs) 1], x);
y1477 = filter([0 sin(2*pi*1477/fs)], [1 -2*cos(2*pi*1477/fs) 1], x);
key = input('Input one of the following keys: 1, 2, 3, 4, 5, 6, 7, 8, 9, *, 0, #
=> ', 's');
yDTMF = [];
switch key
case '1'
yDTMF = y697 + y1209;
case '2'
yDTMF = y697 + y1336;
case '3'
yDTMF = y697 + y1477;
case '4'
yDTMF = y770 + y1209;
case '5'
yDTMF = y770 + y1336;
case '6'
yDTMF = y770 + y1477;
case '7'
yDTMF = y852 + y1209;
case '8'
yDTMF = y852 + y1336;
case '9'
yDTMF = y852 + y1477;
case '*'
yDTMF = y941 + y1209;
case '0'
yDTMF = y941 + y1336;
case '#'
yDTMF = y941 + y1477;
otherwise
disp('Invalid input. Please input a valid DTMF key.');
end
if ~isempty(yDTMF)
subplot(2, 1, 1);
plot(t, yDTMF(1:length(t)));
title(['DTMF Signal for Key "', key, '"']);
xlabel('Time (seconds)');
ylabel('Amplitude');
grid on;
Y = fft(yDTMF);
f = (0:length(Y)-1) * (fs/length(Y));
subplot(2, 1, 2);
plot(f, abs(Y));
title(['Frequency Spectrum of DTMF Signal for Key "', key, '"']);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
xlim([0 2000]);
grid on;
end

You might also like