Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

SIP Assignments

The document provides a comprehensive overview of MATLAB, covering its functionalities, applications, and advantages in computational tasks. It includes detailed sections on matrix manipulation, plotting techniques, signal processing, and the implementation of the Discrete Fourier Transform (DFT). The study emphasizes MATLAB's user-friendly environment, extensive toolboxes, and its relevance in various fields such as engineering, data analysis, and machine learning.

Uploaded by

sohipatel641
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

SIP Assignments

The document provides a comprehensive overview of MATLAB, covering its functionalities, applications, and advantages in computational tasks. It includes detailed sections on matrix manipulation, plotting techniques, signal processing, and the implementation of the Discrete Fourier Transform (DFT). The study emphasizes MATLAB's user-friendly environment, extensive toolboxes, and its relevance in various fields such as engineering, data analysis, and machine learning.

Uploaded by

sohipatel641
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Day1

Study OF MATLAB

MATLAB (Matrix Laboratory) is a high-level programming and interactive environment


developed by MathWorks. It is widely used for numerical computing, data visualization, and
algorithm development. MATLAB is particularly popular in engineering, scientific research,
and education due to its versatility, ease of use, and rich library of built-in functions.
Purpose of the Study
This study aims to explore MATLAB's functionalities, applications, and advantages in
computational tasks. The focus includes:
1. Understanding MATLAB's core features and syntax.
2. Investigating its applications in various fields such as engineering, data analysis, and
machine learning.
3. Evaluating its performance and comparing it with alternative software.
Key Features of MATLAB
1. Interactive Environment: Provides a user-friendly interface for experimentation and
debugging.
2. Matrix-Based Computation: MATLAB is optimized for handling matrices, making
it ideal for linear algebra tasks.
3. Toolboxes: Specialized libraries for domains like signal processing, image
processing, control systems, and machine learning.
4. Visualization Tools: Enables the creation of high-quality plots, graphs, and
animations.

Applications of MATLAB
1. Engineering and Scientific Research:
a. Simulation and modeling of systems (e.g., electrical circuits, mechanical
systems).
b. Data analysis and visualization for experimental results.
1. Signal and Image Processing:
 Processing and analysis of digital signals and images.
 Development of algorithms for noise reduction, feature extraction, etc.
1. Machine Learning and AI:
 Training and deploying machine learning models using built-in tools.

0901EC231118
Day 1
2. Financial Modeli
 Portfolio optimization, risk analysis, and time-series forecasting.
1. Education:
 Aiding students in understanding complex mathematical and engineering concepts.
Advantages of MATLAB
 Ease of Use: Intuitive syntax suitable for beginners and experts alike.
 Extensive Documentation: Comprehensive help files and user community support.
 Versatility: Suited for various applications across disciplines.
 Performance: Optimized for numerical computation and efficient handling of large
datasets.

Each and everything in a MATLAB is a Matrix


If size =1..then 1*1 is the matrix
CLC command is used for Clearing the screen

Menu bar

1 4,6 and 7 5

2
3

0901EC231118
Day 1

1- CURRENT DIRECTORY
2-WORKSPACE
3-COMMAND HISTORY
4-COMMAND WINDOW
5-RESULT WINDOW
6-EDITOR WINDOW (save ,run)
7-FIGURE WINDOW (plots ,images)
“Ver” command is used to find the version of MATLAB
R2024b Means Version is released in 2024 july- december

0901EC231118
Day 2
2) MATRIX MANIPULATION:

Matrix Creation-
% Row vector
row_vector = [1, 2, 3];
% Column vector
column_vector = [1; 2; 3];
% 2x3 matrix
matrix_2x3 = [1, 2, 3; 4, 5, 6];
% 3x3 identity matrix
identity_matrix = eye(3);
% Random 3x3 matrix with values between 0 and 1
random_matrix = rand(3);
% Zero matrix of size 3x3
zero_matrix = zeros(3);

OUTPUT-

0901EC231118
Day 2
Matrix Addition And Substraction-

A = [1, 2; 3, 4];
B = [5, 6; 7, 8];
% Matrix addition
C = A + B;
% Matrix subtraction
D = A - B;

OUTPUT-

0901EC231118
Day 2
Matrix Multiplication-

A = [1, 2; 3, 4];
B = [5, 6; 7, 8];
% Matrix multiplication (dot product)
E = A * B;
% Element-wise multiplication
F = A .* B;
v = [1; 2];

OUTPUT-

0901EC231118
Day 2
Matrix Transpose-

A = [1, 2; 3, 4];
B = A'; % Transpose of A

OUTPUT-

Matrix Inverse-

A = [1, 2; 3, 4];
inv_A = inv(A); % Inverse of A

OUTPUT-

0901EC231118
Day 2
3) PLOTTING SINGLE WAVE-

% time vector
t = 0:0.01:2*pi; % Time from 0 to 2*pi
% sine wave
y = sin(t); % Sine of time vector t
% Plot the sine wave
plot(t, y); % Plot with blue line and width 2
xlabel('Time (seconds)'); % Label for the x-axis
ylabel('Amplitude'); % Label for the y-axis
title('Single Sine Wave'); % Title of the plot

OUTPUT-

0901EC231118
Day2
4) SINE, COSINE AND TAN WAVE-

% Define the time vector


t = 0:0.001:2*pi;

% Define the frequencies


f1 = 1;
f2 = 2;
f3 = 3;

% Sine, Cosine, and Tangent waves


y_sin = sin(2*pi*f1*t); % Sine wave with frequency 1 Hz
y_cos = cos(2*pi*f2*t); % Cosine wave with frequency 2 Hz
y_tan = tan(2*pi*f3*t); % Tangent wave with frequency 3 Hz

% Plot the sine wave


subplot(3,1,1);
plot(t, y_sin);
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Sine Wave (f = 1 Hz)');

% Plot the cosine wave


subplot(3,1,2);
plot(t, y_cos);
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Cosine Wave (f = 2 Hz)');

0901EC231118
Day 2
% Plot the tangent wave
subplot(3,1,3);
plot(t, y_tan);
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Tangent Wave (f = 3 Hz)');
ylim([-10 10]); % Limit the y-axis for better visibility of the tangent wave

OUTPUT-

0901EC231118
Day2
5) SUBPLOTS-

% Define the time vector


t = 0:0.001:2*pi;

% Define the frequencies


f1 = 1;
f2 = 2;

% Create a 3x2 grid of subplots and plot sine waves with different frequencies

% Plot sine wave with frequency f1 in the first subplot


subplot(3,2,1); % Position 1 in a 3x2 grid
y_sin1 = sin(2*pi*f1*t); % Sine wave with frequency f1
plot(t, y_sin1, 'b-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Sine Wave (f = 2 Hz)']);

% Plot sine wave with frequency f2 in the second subplot


subplot(3,2,2); % Position 2 in a 3x2 grid
y_sin2 = sin(2*pi*f2*t); % Sine wave with frequency f2
plot(t, y_sin2, 'r-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Sine Wave (f = ', num2str(f2), ' Hz)']);

0901EC231118
Day 2
% Plot cosine wave with frequency f1 in the third subplot
subplot(3,2,3); % Position 3 in a 3x2 grid
y_cos1 = cos(2*pi*f1*t); % Cosine wave with frequency f1
plot(t, y_cos1, 'g-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Cosine Wave (f = ', num2str(f1), ' Hz)']);

% Plot cosine wave with frequency f2 in the fourth subplot


subplot(3,2,4); % Position 4 in a 3x2 grid
y_cos2 = cos(2*pi*f2*t); % Cosine wave with frequency f2
plot(t, y_cos2, 'm-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Cosine Wave (f = ', num2str(f2), ' Hz)']);

% Plot tangent wave with frequency f1 in the fifth subplot


subplot(3,2,5); % Position 5 in a 3x2 grid
y_tan1 = tan(2*pi*f1*t); % Tangent wave with frequency f1
plot(t, y_tan1, 'c-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Tangent Wave (f = ', num2str(f1), ' Hz)']);
ylim([-10 10]); % Limit y-axis for tangent wave

0901EC231118
Day2
% Plot tangent wave with frequency f2 in the sixth subplot
subplot(3,2,6); % Position 6 in a 3x2 grid
y_tan2 = tan(2*pi*f2*t); % Tangent wave with frequency f2
plot(t, y_tan2, 'y-');
xlabel('Time (seconds)');
ylabel('Amplitude');
title(['Tangent Wave (f = ', num2str(f2), ' Hz)']);
ylim([-10 10]); % Limit y-axis for tangent wave

OUTPUT-

0901EC231118
Day3
% Parameters
Fs = 1000; % Sampling frequency (Hz)
T = 1/Fs; % Sampling period
t = 0:T:1-T; % Time vector for 1 second
f = 50; % Frequency of the signal (Hz)

% Original Signal (Sine wave)


x = sin(2*pi*f*t);

% Time Shift: Shifting by 0.2 seconds


time_shift = 0.2;
t_shifted = t + time_shift;
x_shifted_time = sin(2*pi*f*(t_shifted));

% Frequency Shift: Shift in frequency domain


% Take FFT of the original signal
X = fft(x);
N = length(x);
f_axis = Fs*(0:(N/2))/N; % Frequency axis

% Frequency shift: Multiply by a phase factor for shifting


% We shift the frequency by a certain amount, say 20 Hz.
f_shift = 20;
X_shifted = X .* exp(1j*2*pi*f_shift*t);

0901EC231118
Day 3
% Plot Time Domain Signals
figure;
subplot(2, 1, 1);
plot(t, x, 'b', 'LineWidth', 1.5);
hold on;
plot(t_shifted, x_shifted_time, 'r', 'LineWidth', 1.5);
title('Time Domain: Original and Time Shifting');
xlabel('Time (seconds)');
ylabel('Amplitude');
legend('Original Signal', 'Shifted in Time');

% Plot Frequency Domain Signals


subplot(2, 1, 2);
% Plot original signal's frequency spectrum
X_mag = abs(X(1:N/2+1)); % Magnitude of FFT (half the spectrum)
plot(f_axis, X_mag, 'b', 'LineWidth', 1.5);
hold on;
% Plot shifted signal's frequency spectrum
X_shifted_mag = abs(X_shifted(1:N/2+1)); % Magnitude of shifted FFT
plot(f_axis, X_shifted_mag, 'r', 'LineWidth', 1.5);
title('Frequency Domain: Original and Frequency Shifting');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
legend('Original Signal Spectrum', 'Shifted in Frequency');

0901EC231118
Day

Day3

Sampling
% Parameters
Fs_cont = 1000; % Continuous signal sampling frequency (Hz)
Fs_samp = 500; % Sampling frequency (Hz) for sampling below Nyquist
Fs_samp_high = 1200; % Sampling frequency (Hz) for sampling above Nyquist
T = 1/Fs_cont; % Sampling period for continuous signal (high)
t_cont = 0:T:1-T; % Time vector for continuous signal (1 second duration)

% Signal Definition (Continuous)


f_signal = 400; % Signal frequency (Hz)

0901EC231118
x_cont = sin(2*pi*f_signal*t_cont); % Continuous time signal

% Sampling the signal at two different rates:


% 1. Below Nyquist (Sampling below 2*f_signal = 800 Hz)
t_samp = 0:1/Fs_samp:1-1/Fs_samp;
x_samp = sin(2*pi*f_signal*t_samp);

% 2. Above Nyquist (Sampling above 2*f_signal = 800 Hz)


t_samp_high = 0:1/Fs_samp_high:1-1/Fs_samp_high;
x_samp_high = sin(2*pi*f_signal*t_samp_high);

% Plot the results


figure;

Day 3
% Plot Continuous Signal and Sampled Signals
subplot(2, 1, 1);
plot(t_cont, x_cont, 'b', 'LineWidth', 1.5); hold on;
stem(t_samp, x_samp, 'r', 'LineWidth', 1.5);
title('Signal Sampling - Below Nyquist');
xlabel('Time (seconds)');
ylabel('Amplitude');
legend('Continuous Signal', 'Sampled Signal (Below Nyquist)');
grid on;

0901EC231118
subplot(2, 1, 2);

plot(t_cont, x_cont, 'b', 'LineWidth', 1.5); hold on;


stem(t_samp_high, x_samp_high, 'g', 'LineWidth', 1.5);
title('Signal Sampling - Above Nyquist');
xlabel('Time (seconds)');
ylabel('Amplitude');
legend('Continuous Signal', 'Sampled Signal (Above Nyquist)');
grid on;

% Explain Nyquist Criterion


disp('Nyquist Criterion:');
disp(['For this example, the Nyquist rate is ', num2str(2*f_signal), ' Hz.']);
disp(['Sampling below ', num2str(2*f_signal), ' Hz causes aliasing.']);
disp(['Sampling above ', num2str(2*f_signal), ' Hz avoids aliasing.']);

Day 3

0901EC231118
Day4

MATLAB Code to calculate dft using equation not using fft() function
% Example signal parameters
Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 1000; % Length of the signal
t = (0:L-1)*T; % Time vector

% Example signal (e.g., a sine wave with some noise)


f1 = 50; % Frequency of the sine wave (Hz)
f2 = 150; % Frequency of another sine wave (Hz)
x = 0.7*sin(2*pi*f1*t) + 0.3*sin(2*pi*f2*t) + 0.1*randn(size(t)); % Signal with noise

% Plot the time-domain signal


figure;
subplot(3,1,1);
plot(t, x);
title('Time Domain Signal');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Compute the DFT using the equation (manual implementation)


N = length(x); % Length of the signal
X_dft = zeros(1, N); % Initialize the DFT result

for k = 0:N-1
X_dft(k+1) = sum(x .* exp(-1j * 2 * pi * k * (0:N-1) / N)); % DFT formula end

% Magnitude Spectrum (single-sided)


P2 = abs(X_dft/N); % Two-sided spectrum
P1 = P2(1:N/2+1); % Single-sided spectrum
P1(2:end-1) = 2*P1(2:end-1); % Double the amplitude except at DC and Nyquist

% Frequency vector
f = Fs*(0:(N/2))/N;

% Plot the Magnitude Spectrum


subplot(3,1,2);
plot(f, P1);
title('Magnitude Spectrum (DFT)');
xlabel('Frequency (Hz)');

0901EC231118
ylabel('|X[k]|');

Day 4
% Phase Spectrum
phase_spectrum = angle(X_dft); % Phase of the DFT result (full spectrum)

% Plot the Phase Spectrum


subplot(3,1,3);
plot(f, phase_spectrum(1:N/2+1));
title('Phase Spectrum (DFT)');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)'

Day 4

MATLAB Code for signal conversion from time domain to frequency domain
% Example signal parameters
Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 1000; % Length of the signal
t = (0:L-1)*T; % Time vector

% Example signal (e.g., a sine wave with some noise)


f1 = 50; % Frequency of the sine wave (Hz)
f2 = 150; % Frequency of another sine wave (Hz)
signal = 0.7*sin(2*pi*f1*t) + 0.3*sin(2*pi*f2*t) + 0.1*randn(size(t)); % Signal with noise

% Plot the time-domain signal


figure;
subplot(2,1,1);
plot(t, signal);
title('Time Domain Signal');
0901EC231118
xlabel('Time (seconds)');
ylabel('Amplitude');

% Perform FFT
Y = fft(signal);

% Compute the two-sided spectrum, then compute the single-sided spectrum


P2 = abs(Y/L); % Two-sided spectrum
P1 = P2(1:L/2+1); % Single-sided spectrum
P1(2:end-1) = 2*P1(2:end-1); % Double the amplitude except at DC and Nyquist

% Frequency vector
f = Fs*(0:(L/2))/L;

Day 4

% Plot the frequency-domain representation


subplot(2,1,2);
plot(f, P1);
title('Frequency Domain (Magnitude Spectrum)');
xlabel('Frequency (Hz)');
ylabel('|P1(f)|');

0901EC231118
Day4
MATLAB Code to plot magnitude and phase spectrum of a signal in frequency domain
% Example signal parameters
Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 1000; % Length of the signal
t = (0:L-1)*T; % Time vector

% Example signal (e.g., a sine wave with some noise)


f1 = 50; % Frequency of the sine wave (Hz)
f2 = 150; % Frequency of another sine wave (Hz)
signal = 0.7*sin(2*pi*f1*t) + 0.3*sin(2*pi*f2*t) + 0.1*randn(size(t)); % Signal with noise

% Plot the time-domain signal


figure;
subplot(3,1,1);
plot(t, signal);
title('Time Domain Signal');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Perform FFT
Y = fft(signal);

% Compute the two-sided spectrum, then compute the single-sided spectrum


P2 = abs(Y/L); % Two-sided spectrum
P1 = P2(1:L/2+1); % Single-sided spectrum
P1(2:end-1) = 2*P1(2:end-1); % Double the amplitude except at DC and Nyquist

% Frequency vector
f = Fs*(0:(L/2))/L;

% Magnitude Spectrum Plot


subplot(3,1,2);
plot(f, P1);
title('Magnitude Spectrum');
xlabel('Frequency (Hz)');

0901EC231118
ylabel('|P1(f)|');

Day 4

% Phase Spectrum Plot


phase_spectrum = angle(Y(1:L/2+1)); % Phase of the FFT result (single-sided)
subplot(3,1,3);
plot(f, phase_spectrum);
title('Phase Spectrum');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');

Day 5

Power spectral density distribution

Power Spectral Density (PSD) is a measure of how the power of a signal is distributed across
different frequency components. It represents the power content of a signal as a function of
frequency, providing insight into the signal's frequency content and energy distribution over
the spectrum. PSD is particularly useful in signal processing and communications to analyze
the frequency characteristics of a signal, noise, or any random process.
For discrete signals, the PSD can be computed as the average of the squared magnitudes of
the signal's Fourier coefficients.

Mathematically, the PSD is given by the square of the magnitude of the Fourier transform of
the signal, normalized by the signal length (or total time duration) to get a distribution per
unit frequency.

0901EC231118
Where:
 X(f) is the Fourier transform of the signal,
 f is the frequency variable, and
 T is the duration of the signal.

Day 5
MATLAB Code to calculate Power spectral density distribution
% Example Signal Generation
Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 1000; % Length of the signal
t = (0:L-1)*T; % Time vector

% Example signal (e.g., a sine wave with some noise)


f1 = 50; % Frequency of the sine wave (Hz)
f2 = 150; % Frequency of another sine wave (Hz)
x = 0.7*sin(2*pi*f1*t) + 0.3*sin(2*pi*f2*t) + 0.1*randn(size(t)); % Signal with noise

% Plot the time-domain signal


figure;

0901EC231118
subplot(3,1,1);
plot(t, x);
title('Time Domain Signal');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Compute the FFT of the signal


X = fft(x); % Compute the FFT
N = length(x); % Length of the signal

% Compute the two-sided spectrum


P2 = abs(X/N).^2; % Two-sided spectrum (magnitude squared, normalized)

% Compute the single-sided spectrum


P1 = P2(1:N/2+1); % Single-sided spectrum
P1(2:end-1) = 2*P1(2:end-1); % Double the amplitude except at DC and Nyquist

% Frequency vector (for plotting)


f = Fs*(0:(N/2))/N;

% Plot the PSD (Magnitude in dB)


subplot(3,1,2);
plot(f, 10*log10(P1)); % Plot PSD in dB scale
title('Power Spectral Density (PSD) Estimate');
xlabel('Frequency (Hz)');
ylabel('Power/Frequency (dB/Hz)');

Day 5
% Plot the phase spectrum
phase_spectrum = angle(X); % Compute the phase of the FFT

subplot(3,1,3);
plot(f, phase_spectrum(1:N/2+1)); % Only plot the relevant part
title('Phase Spectrum');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');

0901EC231118
Day 5

Spectogram
A spectrogram is a time-frequency representation of a signal that provides insight into how
its frequency content varies over time. It is a 2D plot that shows the amplitude (or power) of
different frequency components of a signal as they evolve over time. Essentially, a
spectrogram provides a visual representation of the time-varying spectrum of a signal.
A spectrogram is computed by dividing the signal into small segments (windows), typically
using a sliding window approach, and applying the Fourier Transform to each segment. This
results in a matrix where each column represents the frequency content of the signal at a
particular time instant.
How is a Spectrogram Useful in Time-Frequency Analysis?
The spectrogram is particularly useful in time-frequency analysis because it allows the
following:
 Tracking Frequency Changes: It shows how the frequency content of a signal
changes over time, making it useful for non-stationary signals where the frequency
content varies (e.g., speech, music, or transient events).
 Visualizing Non-Stationary Signals: Many real-world signals are non-stationary,
meaning their frequency content changes over time. The spectrogram captures this
time-varying frequency content.
 Analyzing Transients and Events: It helps in detecting and analyzing transient
events or sudden changes in frequency, which is important in fields like audio
analysis, communications, and biomedical signal processing (e.g., EEG, ECG).
 Noise and Signal Separation: It can be used to distinguish between noise and signal
by observing how the frequency content behaves over time.
Code

% Example Signal Generation


Fs = 1000; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 1000; % Length of the signal
t = (0:L-1)*T; % Time vector

% Example signal: A signal with changing frequency

0901EC231118
f1 = 50; % Initial frequency of the sine wave (Hz)
f2 = 150; % Final frequency of the sine wave (Hz)
x = sin(2*pi*f1*t) + sin(2*pi*f2*(t+1)); % Signal with changing frequencies

Day 5

% Plot the time-domain signal


figure;
subplot(3,1,1);
plot(t, x);
title('Time Domain Signal');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Parameters for Spectrogram Calculation


window_size = 256; % Length of the window
overlap = 128; % Number of overlapping samples
nfft = 512; % Number of FFT points

% Number of windows
num_windows = floor((L - window_size) / (window_size - overlap)) + 1;

% Initialize matrix to store spectrogram


S = zeros(nfft, num_windows);

% Compute the spectrogram using FFT


for i = 1:num_windows
% Define the start and end of the current window
start_idx = (i - 1) * (window_size - overlap) + 1;
end_idx = start_idx + window_size - 1;

% Extract the current windowed segment of the signal


segment = x(start_idx:end_idx);

% Apply FFT to the segment


X = fft(segment, nfft);

0901EC231118
% Store the magnitude squared (Power Spectrum)
S(:, i) = abs(X).^2; end

% Frequency vector for plotting


f = Fs * (0:(nfft/2)) / nfft;

% Time vector for plotting (corresponding to the center of each window)


time = (window_size/2:(window_size-overlap):L-window_size/2) * T;

Day 5

% Plot the Spectrogram (in dB scale)


subplot(3,1,2);
imagesc(time, f, 10*log10(S(1:nfft/2+1, :))); % Convert to dB scale
axis xy; % Flip the y-axis for correct orientation
title('Spectrogram');
xlabel('Time (seconds)');
ylabel('Frequency (Hz)');
colorbar;
colormap jet; % Color map for better visualization

% Plot the Phase Spectrum of the Signal


subplot(3,1,3);
phase_spectrum = angle(fft(x, nfft)); % Phase spectrum of the entire signal
plot(f, phase_spectrum(1:nfft/2+1)); % Phase for positive frequencies
title('Phase Spectrum');
xlabel('Frequency (Hz)');
ylabel('Phase (radians)');

Day 5
MATLAB Code to show fft and spectrogram of a EEG/ECG signal.

% Load or Generate ECG Signal (using PhysioNet dataset or synthetic ECG)


% For demonstration purposes, let's generate a synthetic ECG-like signal.

0901EC231118
% Simulation parameters
Fs = 500; % Sampling frequency in Hz
T = 1/Fs; % Sampling period
L = 5000; % Length of the signal (10 seconds of ECG)
t = (0:L-1)*T; % Time vector

% Generate a synthetic ECG signal (simulating a typical ECG waveform)


% For simplicity, let's create a sinusoidal approximation with noise
% Real ECG signals can be loaded from files like 'ECG.mat' or a PhysioNet database.
ecg_signal = 0.6 * sin(2*pi*1.2 * t) + 0.2 * sin(2*pi*1.6 * t) + 0.1*randn(size(t)); %
Simulated ECG

% Plot the time-domain ECG signal


figure;
subplot(3,1,1);
plot(t, ecg_signal);
title('Simulated ECG Signal in Time Domain');
xlabel('Time (seconds)');
ylabel('Amplitude');

% Perform FFT on the entire ECG signal to analyze frequency content


N = length(ecg_signal); % Length of the signal
ecg_fft = fft(ecg_signal); % FFT of the ECG signal
f = Fs * (0:(N/2)) / N; % Frequency vector

% Compute the single-sided spectrum


P2 = abs(ecg_fft / N).^2; % Two-sided spectrum
P1 = P2(1:N/2+1); % Single-sided spectrum
P1(2:end-1) = 2*P1(2:end-1); % Double the amplitude for non-DC and Nyquist components

% Plot the FFT magnitude spectrum


subplot(3,1,2);
plot(f, 10*log10(P1)); % Plot the spectrum in dB scale
title('Frequency Domain Representation (FFT)');
xlabel('Frequency (Hz)');
ylabel('Power/Frequency (dB/Hz)');

Day 5
% Spectrogram Calculation (Time-Frequency Analysis)
window_size = 256; % Length of the window (samples)
overlap = 128; % Overlap between windows (samples)

0901EC231118
nfft = 512; % Number of FFT points

% Calculate the spectrogram


[S, F, T_spec] = spectrogram(ecg_signal, window_size, overlap, nfft, Fs);

% Plot the Spectrogram

subplot(3,1,3);

imagesc(T_spec, F, 10*log10(abs(S))); % Convert to dB scale

axis xy; % Flip the y-axis to have low frequencies at the


bottom

title('ECG Signal Spectrogram');

xlabel('Time (seconds)');

ylabel('Frequency (Hz)');

colorbar; % Display color scale

colormap jet; % Color map for better visualization

Day 6 and Day 7


1. filter()
The filter() function in MATLAB is used to apply a digital filter to a signal. It performs a
one-pass filtering operation, meaning it processes the input signal in a forward direction only
(no phase correction). The general syntax is:
matlab

y = filter(b, a, x)
 b is the numerator coefficient vector (or the feedforward coefficients) of the filter.
 a is the denominator coefficient vector (or the feedback coefficients) of the filter.
 x is the input signal to be filtered.
 y is the output signal (filtered version of x).
In simple terms, filter() processes the input signal x with the defined filter (described by b
and a), producing an output y.
2. filtfilt()

0901EC231118
The filtfilt() function in MATLAB performs a zero-phase filtering operation by applying the
filter forwards and then backwards. This helps remove phase distortion. It is particularly
useful when you want to preserve the shape of the signal and avoid any phase shift.
The syntax is:
matlab

y = filtfilt(b, a, x)
 Similar to filter(), b and a are the filter coefficients, and x is the input signal.
 The difference with filter() is that filtfilt() applies the filter in both directions (forward
and reverse), resulting in a signal with no phase shift but still preserving the
magnitude response.
This function is useful when you want to minimize phase distortion while filtering your
signal.
3. freqz()
The freqz() function is used to compute and plot the frequency response of a digital filter. It
shows how the filter will affect the frequencies in a signal. It's especially useful when you
want to visualize the magnitude and phase response of the filter.
The syntax is:
matlab

[H, W] = freqz(b, a, N)
 b and a are the filter coefficients (numerator and denominator).
 N is the number of points used for plotting the frequency response (if not specified, a
default value is used).
 H is the frequency response (complex values).

Day 6 and Day 7

 W is the frequency values (normalized frequency in radians per sample).


You can then plot the magnitude and phase of the response using abs(H) for magnitude and
angle(H) for phase. This is important when designing filters to see how they behave across
different frequencies.
4. fir1()
The fir1() function is used to design a simple Finite Impulse Response (FIR) filter. It is a
straightforward way to create an FIR filter using the windowing method. It returns the filter
coefficients (numerator) b, which can then be used with the filter() or filtfilt() functions.
The syntax is:
Matlab

b = fir1(N, Wn, 'type', window)

0901EC231118
 N is the order of the filter (number of taps minus one).
 Wn is the cutoff frequency (or frequencies) normalized between 0 and 1 (where 1 is
half the sampling rate).
 'type' specifies the filter type, like 'low', 'high', 'bandpass', or 'stop'.
 window (optional) specifies the windowing function to use (like Hamming, Hanning,
etc.) to design the filter.

For example, to design a low-pass FIR filter with a cutoff frequency of 0.2 (normalized):
Matlab

b = fir1(20, 0.2, 'low');


5. butter()
The butter() function is used to design an Infinite Impulse Response (IIR) filter using the
Butterworth filter design method. A Butterworth filter is known for having a flat frequency
response in the passband, which makes it popular for many filtering applications.
The syntax is:
matlab

[b, a] = butter(N, Wn, 'type')


 N is the order of the filter.
 Wn is the cutoff frequency (or frequency range for bandpass and bandstop filters),
normalized between 0 and 1.
 'type' specifies the filter type ('low', 'high', 'bandpass', or 'bandstop').
For example, to design a 4th-order low-pass Butterworth filter with a cutoff frequency of 0.4:

Day 6 and Day 7


matlab

[b, a] = butter(4, 0.4, 'low');


Once the filter coefficients b and a are calculated, you can use the filter() function to apply
the filter to a signal.

0901EC231118
Day 6 and Day 7
MATLAB Code to design a filter and apply on the signal for Noise reduction
% 1. Generate a clean signal (sine wave) and add noise
fs = 1000; % Sampling frequency (Hz)
t = 0:1/fs:1-1/fs; % Time vector (1 second duration)
f_clean = 50; % Frequency of the clean signal (Hz)
clean_signal = sin(2*pi*f_clean*t); % Clean sine wave signal

% Add random noise (white noise)

0901EC231118
noise = 0.5 * randn(size(t)); % Gaussian white noise
noisy_signal = clean_signal + noise; % Noisy signal

% Plot the clean and noisy signals


figure;
subplot(3,1,1);
plot(t, clean_signal);
title('Clean Signal');
xlabel('Time (s)');
ylabel('Amplitude');

subplot(3,1,2);
plot(t, noisy_signal);
title('Noisy Signal');
xlabel('Time (s)');
ylabel('Amplitude');

Day 6 and Day7


% 2. Design a low-pass FIR filter using fir1()
% FIR filter with a cutoff frequency of 100 Hz
cutoff_fir = 100 / (fs/2); % Normalized cutoff frequency
order_fir = 50; % Filter order
b_fir = fir1(order_fir, cutoff_fir, 'low'); % FIR filter coefficients

% Apply the FIR filter using filter()


filtered_signal_fir = filter(b_fir, 1, noisy_signal)
0901EC231118
% 3. Design a low-pass IIR filter using butter()
% IIR filter with a cutoff frequency of 100 Hz
cutoff_iir = 100 / (fs/2); % Normalized cutoff frequency
order_iir = 4; % Filter order
[b_iir, a_iir] = butter(order_iir, cutoff_iir, 'low'); % Butterworth IIR filter coefficients

% Apply the IIR filter using filter()


filtered_signal_iir = filter(b_iir, a_iir, noisy_signal);

% 4. Plot the filtered signals


subplot(3,1,3);
plot(t, filtered_signal_fir, 'r', 'LineWidth', 1.5); hold on;
plot(t, filtered_signal_iir, 'g', 'LineWidth', 1.5);
legend('FIR Filtered', 'IIR Filtered');
title('Filtered Signals (FIR and IIR)');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

Day 6 and Day7


% Display message
disp('Filtering process completed.');
Output:-

0901EC231118

You might also like