0% found this document useful (0 votes)
12 views21 pages

MATLAB Code

dsp code

Uploaded by

saurish gahlaut
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views21 pages

MATLAB Code

dsp code

Uploaded by

saurish gahlaut
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

MATLAB Code for Linear Convolution, Cross-Correlation, and Auto-Correlation

Linear Convolution
Using Built-in Function
% Define two discrete signals
x = [1, 2, 3, 4];
h = [2, 1];

% Linear convolution using built-in function


linear_conv_builtin = conv(x, h);

% Display the result


disp('Linear Convolution (using built-in function):');
disp(linear_conv_builtin);

Without Using Built-in Function


% Define two discrete signals
x = [1, 2, 3, 4];
h = [2, 1];

% Get the lengths of the signals


N = length(x);
M = length(h);
L = N + M - 1; % Length of the result

% Zero-pad the signals to the result length


x_padded = [x, zeros(1, M - 1)];
h_padded = [h, zeros(1, N - 1)];

% Linear convolution calculation (manual)


linear_conv_manual = zeros(1, L);
for n = 1:L % Iterate over each output sample
for m = 1:N % Iterate over each element of x
if (n - m + 1 > 0) % Check if the index is valid
linear_conv_manual(n) = linear_conv_manual(n) + x_padded(m) * h_padded(n - m + 1);
end
end
end

% Display the result


disp('Linear Convolution (manual calculation):');
disp(linear_conv_manual);
Cross-Correlation
Using Built-in Function
% Define two discrete signals
x = [1, 2, 3, 4];
y = [4, 3, 2, 1];

% Cross-correlation using built-in function


cross_corr_builtin = xcorr(x, y);

% Display the result


disp('Cross-correlation (using built-in function):');
disp(cross_corr_builtin);

Without Using Built-in Function


% Define two discrete signals
x = [1, 2, 3, 4];
y = [4, 3, 2, 1];

% Get the lengths of the signals


N = length(x);
M = length(y);
L = N + M - 1; % Length of the result

% Zero-pad the signals to the result length


x_padded = [x, zeros(1, M - 1)];
y_padded = [y, zeros(1, N - 1)];

% Cross-correlation calculation (manual)


cross_corr_manual = zeros(1, L);
for n = 1:L % Iterate over each output sample
for m = 1:N % Iterate over each element of x
if (n - m + 1 > 0 && n - m + 1 <= M) % Check if the index is valid for y
cross_corr_manual(n) = cross_corr_manual(n) + x_padded(m) * y_padded(n - m + 1);
end
end
end

% Display the result


disp('Cross-correlation (manual calculation):');
disp(cross_corr_manual);

Auto-Correlation
Using Built-in Function
% Define a discrete signal
x = [1, 2, 3, 4];

% Auto-correlation using built-in function


auto_corr_builtin_x = xcorr(x);

% Display the result


disp('Auto-correlation of x (using built-in function):');
disp(auto_corr_builtin_x);

Without Using Built-in Function


% Define a discrete signal
x = [1, 2, 3, 4];

% Get the length of the signal


N = length(x);
L = 2 * N - 1; % Length of the result

% Zero-pad the signal to the result length


x_padded = [x, zeros(1, N - 1)];

% Auto-correlation calculation (manual)


auto_corr_manual_x = zeros(1, L);
for n = 1:L % Iterate over each output sample
for m = 1:N % Iterate over each element of x
if (n - m + 1 > 0 && n - m + 1 <= N) % Check if the index is valid
auto_corr_manual_x(n) = auto_corr_manual_x(n) + x_padded(m) * x_padded(n - m + 1);
end
end
end

% Display the result


disp('Auto-correlation of x (manual calculation):');
disp(auto_corr_manual_x);

Matlab Code for ODE

% Define the parameters

k = 0.1; % Decay constant

y0 = 10; % Initial condition y(0) = 10

% Define the ODE as a function handle


odefun = @(t, y) -k * y;

% Set the time span for the solution

tspan = [0 50]; % From t = 0 to t = 50

% Solve the ODE using ode45

[t, y] = ode45(odefun, tspan, y0);

% Plot the results

figure;

plot(t, y, 'LineWidth', 2);

xlabel('Time (t)');

ylabel('Function value (y)');

title('Solution of ODE dy/dt = -ky');

grid on;

MATLAB Code to Find the Impulse Response

% Define the system (transfer function coefficients)

b = [0.5, 1]; % Numerator coefficients (for example, H(z) = 0.5 + z^-1)

a = [1, -0.3]; % Denominator coefficients (H(z) = (0.5 + z^-1)/(1 - 0.3z^-1))

% 1. Using impz to find impulse response

figure;

subplot(3, 1, 1);

impz(b, a); % Impulse response of the system


title('Impulse Response using impz');

xlabel('Samples');

ylabel('Amplitude');

% 2. Using filter to find impulse response

n_samples = 100; % Number of samples for the impulse response

impulse = [1; zeros(n_samples-1, 1)]; % Create an impulse signal

response_filter = filter(b, a, impulse); % Filter the impulse

subplot(3, 1, 2);

stem(response_filter); % Plot the response

title('Impulse Response using filter');

xlabel('Samples');

ylabel('Amplitude');

% 3. Using deconv to find impulse response

response_deconv = deconv(response_filter, impulse); % Deconvolve to find response

subplot(3, 1, 3);

stem(response_deconv); % Plot the response

title('Impulse Response using deconv');

xlabel('Samples');

ylabel('Amplitude');

% Adjust the layout

sgtitle('Impulse Response of LTI System using Different Methods');

MATLAB Code to Compute DFT and IDFT


% Define the input discrete time sequence

x = [1, 2, 3, 4]; % Example discrete time sequence

% 1. Compute the DFT of the sequence

N = length(x); % Length of the input sequence

X = zeros(1, N); % Initialize the DFT output array

for k = 0:N-1

for n = 0:N-1

% Compute the DFT using the formula

X(k+1) = X(k+1) + x(n+1) * exp(-1j * 2 * pi * k * n / N);

end

end

% Display the DFT result

disp('DFT of the input sequence:');

disp(X);

% 2. Compute the IDFT of the sequence

x_reconstructed = zeros(1, N); % Initialize the IDFT output array

for n = 0:N-1

for k = 0:N-1

% Compute the IDFT using the formula

x_reconstructed(n+1) = x_reconstructed(n+1) + X(k+1) * exp(1j * 2 * pi * k * n / N);

end

x_reconstructed(n+1) = x_reconstructed(n+1) / N; % Normalize the result


end

% Display the IDFT result

disp('Reconstructed sequence from IDFT:');

disp(x_reconstructed);

% Plot the original sequence

figure;

subplot(3, 1, 1);

stem(0:N-1, x, 'filled');

title('Original Discrete Time Sequence');

xlabel('Sample Index');

ylabel('Amplitude');

% Plot the magnitude of the DFT result

subplot(3, 1, 2);

stem(0:N-1, abs(X), 'filled');

title('Magnitude Spectrum of DFT');

xlabel('Frequency Index');

ylabel('Magnitude');

% Plot the reconstructed sequence from IDFT

subplot(3, 1, 3);

stem(0:N-1, real(x_reconstructed), 'filled'); % Use real part to avoid numerical noise

title('Reconstructed Sequence from IDFT');

xlabel('Sample Index');

ylabel('Amplitude');
% Adjust layout

sgtitle('DFT and IDFT Results');

MATLAB Code to Compute FFT and IFFT of the Signal

% Parameters for the signal

fs = 10000; % Sampling frequency in Hz

N = 1024; % Number of points for FFT

n = 0:N-1; % Sample index

% Define the signal X[n] = cos(2*pi*1000*n/fs) + cos(2*pi*500*n/fs)

X_n = cos(2 * pi * 1000 * n / fs) + cos(2 * pi * 500 * n / fs);

% Compute the FFT of the signal

X_fft = fft(X_n);

% Compute the IFFT of the signal to reconstruct it

X_ifft = ifft(X_fft);

% Plot the original signal

figure;

subplot(3, 1, 1);

plot(n, X_n);

title('Original Signal X[n]');

xlabel('Sample Index');

ylabel('Amplitude');
% Plot the magnitude spectrum of the FFT

subplot(3, 1, 2);

f = (0:N-1) * (fs / N); % Frequency vector

plot(f, abs(X_fft));

title('Magnitude Spectrum of FFT');

xlabel('Frequency (Hz)');

ylabel('Magnitude');

% Plot the reconstructed signal from IFFT

subplot(3, 1, 3);

plot(n, real(X_ifft));

title('Reconstructed Signal from IFFT');

xlabel('Sample Index');

ylabel('Amplitude');

% Adjust layout

sgtitle('FFT and IFFT of X[n]');

MATLAB Code for Circular Convolution

% Define two finite-duration discrete signals

x = [1, 2, 3, 4]; % First input sequence

h = [1, 1, 1]; % Second input sequence

% Perform circular convolution using inbuilt function

N = max(length(x), length(h)); % Length of the circular convolution

y_circular_inbuilt = cconv(x, h, N);


% Display the result

disp('Circular Convolution using inbuilt function:');

disp(y_circular_inbuilt);

% Define two finite-duration discrete signals

x = [1, 2, 3, 4]; % First input sequence

h = [1, 1, 1]; % Second input sequence

% Zero-pad both sequences to the length of N

N = max(length(x), length(h)); % Length of the circular convolution

x = [x, zeros(1, N - length(x))];

h = [h, zeros(1, N - length(h))];

% Initialize the result array

y_circular_manual = zeros(1, N);

% Perform circular convolution manually

for n = 1:N

for m = 1:N

% Use modulo operation for circular indexing

index = mod(n - m, N);

if index < 0

index = index + N; % Ensure positive indexing

end

y_circular_manual(n) = y_circular_manual(n) + x(m) * h(index + 1);

end
end

% Display the result

disp('Circular Convolution without using inbuilt function:');

disp(y_circular_manual);

MATLAB Code to Design FIR Filters Using Window Techniques

% Sampling frequency

fs = 1000; % Hz

% Normalized cutoff frequencies (relative to Nyquist frequency)

f_cutoff_low = 0.2; % 0.2 * (fs/2) = 100 Hz

f_cutoff_high = 0.5; % 0.5 * (fs/2) = 250 Hz

filter_order = 50; % Filter order

% Frequency specifications for band-pass and band-stop filters

f_band = [0.2, 0.5]; % 100 Hz to 250 Hz

% Designing the filters

% Low-pass filter

lp_rectangular = fir1(filter_order, f_cutoff_low, 'low', rectwin(filter_order + 1));

lp_hanning = fir1(filter_order, f_cutoff_low, 'low', hanning(filter_order + 1));

lp_hamming = fir1(filter_order, f_cutoff_low, 'low', hamming(filter_order + 1));

lp_blackman = fir1(filter_order, f_cutoff_low, 'low', blackman(filter_order + 1));

% High-pass filter

hp_rectangular = fir1(filter_order, f_cutoff_low, 'high', rectwin(filter_order + 1));


hp_hanning = fir1(filter_order, f_cutoff_low, 'high', hanning(filter_order + 1));

hp_hamming = fir1(filter_order, f_cutoff_low, 'high', hamming(filter_order + 1));

hp_blackman = fir1(filter_order, f_cutoff_low, 'high', blackman(filter_order + 1));

% Band-pass filter

bp_rectangular = fir1(filter_order, f_band, 'bandpass', rectwin(filter_order + 1));

bp_hanning = fir1(filter_order, f_band, 'bandpass', hanning(filter_order + 1));

bp_hamming = fir1(filter_order, f_band, 'bandpass', hamming(filter_order + 1));

bp_blackman = fir1(filter_order, f_band, 'bandpass', blackman(filter_order + 1));

% Band-stop filter

bs_rectangular = fir1(filter_order, f_band, 'stop', rectwin(filter_order + 1));

bs_hanning = fir1(filter_order, f_band, 'stop', hanning(filter_order + 1));

bs_hamming = fir1(filter_order, f_band, 'stop', hamming(filter_order + 1));

bs_blackman = fir1(filter_order, f_band, 'stop', blackman(filter_order + 1));

% Plotting frequency responses

figure;

freqz(lp_rectangular, 1, 1024, fs);

title('Low-Pass Filter using Rectangular Window');

figure;

freqz(lp_hanning, 1, 1024, fs);

title('Low-Pass Filter using Hanning Window');

figure;

freqz(lp_hamming, 1, 1024, fs);


title('Low-Pass Filter using Hamming Window');

figure;

freqz(lp_blackman, 1, 1024, fs);

title('Low-Pass Filter using Blackman Window');

MATLAB Code to Design IIR Filters

% Sampling frequency

fs = 2000; % Hz

% Normalized cutoff frequencies (relative to Nyquist frequency)

f_cutoff_low = 0.2; % 0.2 * (fs/2) = 200 Hz

f_cutoff_high = 0.5; % 0.5 * (fs/2) = 500 Hz

f_band = [0.2, 0.5]; % 200 Hz to 500 Hz

% Filter order

filter_order = 4; % Chosen filter order for demonstration

% Butterworth Filter

[b_butter_low, a_butter_low] = butter(filter_order, f_cutoff_low, 'low');

[b_butter_high, a_butter_high] = butter(filter_order, f_cutoff_low, 'high');

[b_butter_band, a_butter_band] = butter(filter_order, f_band, 'bandpass');

[b_butter_stop, a_butter_stop] = butter(filter_order, f_band, 'stop');

% Chebyshev Type I Filter

[b_cheby1_low, a_cheby1_low] = cheby1(filter_order, 0.5, f_cutoff_low, 'low');

[b_cheby1_high, a_cheby1_high] = cheby1(filter_order, 0.5, f_cutoff_low, 'high');


[b_cheby1_band, a_cheby1_band] = cheby1(filter_order, 0.5, f_band, 'bandpass');

[b_cheby1_stop, a_cheby1_stop] = cheby1(filter_order, 0.5, f_band, 'stop');

% Chebyshev Type II Filter

[b_cheby2_low, a_cheby2_low] = cheby2(filter_order, 20, f_cutoff_low, 'low');

[b_cheby2_high, a_cheby2_high] = cheby2(filter_order, 20, f_cutoff_low, 'high');

[b_cheby2_band, a_cheby2_band] = cheby2(filter_order, 20, f_band, 'bandpass');

[b_cheby2_stop, a_cheby2_stop] = cheby2(filter_order, 20, f_band, 'stop');

% Elliptic Filter

[b_ellip_low, a_ellip_low] = ellip(filter_order, 0.5, 20, f_cutoff_low, 'low');

[b_ellip_high, a_ellip_high] = ellip(filter_order, 0.5, 20, f_cutoff_low, 'high');

[b_ellip_band, a_ellip_band] = ellip(filter_order, 0.5, 20, f_band, 'bandpass');

[b_ellip_stop, a_ellip_stop] = ellip(filter_order, 0.5, 20, f_band, 'stop');

% Plotting frequency responses

figure;

freqz(b_butter_low, a_butter_low, 1024, fs);

title('Butterworth Low-Pass Filter');

figure;

freqz(b_cheby1_low, a_cheby1_low, 1024, fs);

title('Chebyshev Type I Low-Pass Filter');

figure;

freqz(b_cheby2_low, a_cheby2_low, 1024, fs);

title('Chebyshev Type II Low-Pass Filter');


figure;

freqz(b_ellip_low, a_ellip_low, 1024, fs);

title('Elliptic Low-Pass Filter');

First experiment

% Clear workspace and close all figures

clear; close all; clc;

%% Continuous-Time Signals

% Define time vector for continuous-time signals

t_continuous = 0:0.01:2; % Time from 0 to 2 seconds with 0.01s interval

% Define continuous-time signals

signal_sine = sin(2 * pi * 1 * t_continuous); % 1 Hz sine wave

signal_square = square(2 * pi * 1 * t_continuous); % 1 Hz square wave

signal_exponential = exp(-t_continuous); % Exponential decay

% Plot continuous-time signals

figure;

subplot(3, 1, 1);

plot(t_continuous, signal_sine, 'LineWidth', 1.5);

title('Continuous-Time Signal: Sine Wave (1 Hz)');

xlabel('Time (s)');

ylabel('Amplitude');
grid on;

subplot(3, 1, 2);

plot(t_continuous, signal_square, 'LineWidth', 1.5);

title('Continuous-Time Signal: Square Wave (1 Hz)');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

subplot(3, 1, 3);

plot(t_continuous, signal_exponential, 'LineWidth', 1.5);

title('Continuous-Time Signal: Exponential Decay');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

%% Discrete-Time Signals

% Define discrete time vector

n_discrete = 0:0.1:2; % Discrete time from 0 to 2 seconds with 0.1s interval

% Define discrete-time signals

discrete_signal_sine = sin(2 * pi * 1 * n_discrete); % 1 Hz sine wave

discrete_signal_square = square(2 * pi * 1 * n_discrete); % 1 Hz square wave

discrete_signal_exponential = exp(-n_discrete); % Exponential decay

% Plot discrete-time signals

figure;
subplot(3, 1, 1);

stem(n_discrete, discrete_signal_sine, 'filled', 'LineWidth', 1.5);

title('Discrete-Time Signal: Sine Wave (1 Hz)');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;

subplot(3, 1, 2);

stem(n_discrete, discrete_signal_square, 'filled', 'LineWidth', 1.5);

title('Discrete-Time Signal: Square Wave (1 Hz)');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;

subplot(3, 1, 3);

stem(n_discrete, discrete_signal_exponential, 'filled', 'LineWidth', 1.5);

title('Discrete-Time Signal: Exponential Decay');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;

%% Basic Elementary Discrete-Time Functions

% Define time vector for basic functions

n_basic = -5:5; % Range from -5 to 5

% Define basic discrete-time functions


impulse_signal = (n_basic == 0); % Impulse function

step_signal = (n_basic >= 0); % Step function

ramp_signal = n_basic .* (n_basic >= 0); % Ramp function

% Plot basic elementary functions

figure;

subplot(3, 1, 1);

stem(n_basic, impulse_signal, 'filled', 'LineWidth', 1.5);

title('Elementary Function: Discrete-Time Impulse Function');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;

subplot(3, 1, 2);

stem(n_basic, step_signal, 'filled', 'LineWidth', 1.5);

title('Elementary Function: Discrete-Time Step Function');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;

subplot(3, 1, 3);

stem(n_basic, ramp_signal, 'filled', 'LineWidth', 1.5);

title('Elementary Function: Discrete-Time Ramp Function');

xlabel('n (Samples)');

ylabel('Amplitude');

grid on;
Second experiment

% Define the input signal

t = 0:0.01:1; % Time vector from 0 to 1 seconds with 0.01s interval

input_signal = sin(2 * pi * 5 * t); % Example input signal (5 Hz sine wave)

% Scaling Transformation

scale_factor = 2; % Scale factor for amplitude

scaled_signal = scale_factor * input_signal;

% Time Shifting Transformation

time_shift = 0.1; % Time shift in seconds

t_shifted = t + time_shift; % Shift time vector

time_shifted_signal = sin(2 * pi * 5 * (t_shifted)); % Time-shifted signal

% Time Reversal Transformation

reversed_signal = fliplr(input_signal); % Reverse the input signal

t_reversed = fliplr(t); % Reverse the time vector

% Frequency Shifting Transformation (Modulation)

frequency_shift = 2; % Frequency shift amount

modulated_signal = cos(2 * pi * frequency_shift * t) .* input_signal; % Modulation with cosine

% Filter Transformation

fs = 100; % Sampling frequency

fc = 10; % Cut-off frequency

[b, a] = butter(2, fc/(fs/2)); % 2nd-order Butterworth filter design

filtered_signal = filter(b, a, input_signal); % Apply the filter


% Visualization

figure;

% Original Signal

subplot(5, 1, 1);

plot(t, input_signal, 'LineWidth', 1.5);

title('Original Signal (5 Hz Sine Wave)');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

% Scaled Signal

subplot(5, 1, 2);

plot(t, scaled_signal, 'LineWidth', 1.5);

title('Scaled Signal (Amplitude x2)');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

% Time-Shifted Signal

subplot(5, 1, 3);

plot(t_shifted, time_shifted_signal, 'LineWidth', 1.5);

title('Time-Shifted Signal (Shifted by 0.1s)');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;
% Reversed Signal

subplot(5, 1, 4);

plot(t_reversed, reversed_signal, 'LineWidth', 1.5);

title('Time-Reversed Signal');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

% Filtered Signal

subplot(5, 1, 5);

plot(t, filtered_signal, 'LineWidth', 1.5);

title('Filtered Signal (Low-Pass Filter)');

xlabel('Time (s)');

ylabel('Amplitude');

grid on;

You might also like