VISVESVARAYA TECHNOLOGICAL UNIVERSITY
BELAGAVI, KARNATAKA, INDIA
An Autonomous Institution with A+ Grade UGC by NAAC UGC, Approved by UGC,
AICTE, Government of Karnataka, Yelahanka, Bengaluru-560064, Karnatka, India.
Internship Report On
MATLAB KPIT WORKSHOP
An Internship Report submitted in partial fulfillment of the requirement for the
award of
BACHELOR OF ENGINEERING
in
ELECTRONICS AND COMMUNICATION
ENGINEERING 2023-2024
Submitted By
Aditya Chug 1NT21EC004
Under the Guidance of
Dr. Rajani N
Assistant Professor
Dept. of Electronics and communication Engineering
An Autonomous Institution with A+ Grade UGC by NAAC UGC, Approved by UGC,
AICTE, Government of Karnataka, Yelahanka, Bengaluru-560064, Karnatka, India.
Department of Electronics and Communication Engineering
Certificate
This is to certify that Aditya chug(1NT21EC004) has submitted the Internship report
entitled “MATLAB KPIT WORKSHOP” in fulfillment for the award of Bachelor of
Engineering in Electronics and Communication Engineering from Visvesvaraya
Technological University, Belagavi during the year 2023-2024. It is certified that all the
corrections and suggestions indicated for internal assessment have been incorporated in
the report. The Internship report has been approved as it satisfies the academic
requirements in respect of work prescribed for the aforesaid degree.
Dr.Rajani N Dr. Parameshachari B D Dr. H. C. Nagaraj
Guide HOD Principal
External Viva Voce
Name of Examiners Signature with Date
1)
2)
Internship Certificate
Acknowledgement
It is my proud privilege and duty to acknowledge the kind help and guidance received from
several people in the preparation of this report. It would not have been possible to prepare
this report in this form without valuable suggestions, cooperation, and guidance.
I wish to record my sincere gratitude to Management, and Dr. H. C. Nagaraj, Principal,
Nitte Meenakshi Institute of Technology, Bengaluru for the permission provided to
accomplish this internship.
My sincere thanks to Dr. Parameshachari B. D., Professor and Head, Department of
Electronics and Communication Engineering for his valuable suggestions and guidance.
My sincere gratitude to Dr. Thimmaraja Yadava G, Dr. Vinaykumar R and Dr. Rajani
N, Internship Coordinators, Department of Electronics and Communication Engineering,
for their valuable suggestions in preparing this report.
I express my sincere gratitude to our beloved guide, Dr.Rajani N(Assistant Professor),
Department of Electronics and Communication and Engineering for his/her support and
guidance.
I am extremely greatful to faculty members of Department of Electronics and
Communication Engineering, and friends for their support and encouragement in
successful completion of this internship.
ADITYA CHUG 1NT21EC004
CONTENTS
1. Introduction to Matlab 1
2. About the Domain 2-4
3. Work Carried Out 5-22
4. Day 1: MATLAB Environment & Basics
Day 2: Advanced MATLAB Programming
Day 3: Data Analysis and Visualization
Day 4: Simulink
Day 5: Project Work and Final Presentation
Project 1-Real time Edge Detection
Project 2-Modulation and Demodulation Techniques
5. Conclusion
6. Reference
DOMAINS OF MATLAB
Numerical Analysis: MATLAB excels in numerical computations, such as solving
differential equations, integration, and matrix manipulation.
Signal Processing: MATLAB provides toolboxes for signal processing tasks such as
filtering, Fourier transforms, and wavelet analysis. It's commonly used for audio and
communication systems design.
Image Processing and Computer Vision: MATLAB offers robust libraries and
functions for image analysis, pattern recognition, and feature extraction, making it valuable
in areas like medical imaging, surveillance, and machine vision.
Control Systems: MATLAB’s Control System Toolbox is widely used to design,
simulate, and analyze control systems. Applications include automation, robotics, and
aerospace engineering.
Machine Learning and AI: MATLAB supports machine learning algorithms and
workflows for classification, clustering, regression, and deep learning. Its integration with
TensorFlow and PyTorch also allows for AI development.
Simulation and Modeling: Through Simulink, MATLAB supports graphical simulation
and modeling of dynamic systems. This is particularly useful in mechanical, electrical, and
aerospace engineering.
Financial Modeling: MATLAB is used for quantitative analysis in finance, such as
portfolio management, risk analysis, and derivative pricing.
Robotics: MATLAB is used to simulate, design, and develop robotic systems, and it
includes interfaces for working with hardware such as drones and robotic arms.
Bioinformatics: MATLAB is utilized for data analysis, modeling, and visualization in the
life sciences, helping in tasks like DNA sequence analysis and protein modeling.
Embedded Systems: MATLAB is used to generate code for real-time embedded systems,
especially in automotive and aerospace applications.
Education and Research: MATLAB is widely used in academic settings for teaching
mathematical concepts, algorithm development, and research.
Introduction to Matlab
MATLAB (Matrix Laboratory) is a high-level programming language and computing environment
developed by MathWorks. It is widely used for numerical computation, data analysis, algorithm
development, and visualization. MATLAB’s strengths lie in its ability to handle matrices and arrays
effortlessly, making it ideal for tasks involving linear algebra, signal processing, control systems, and
image processing.
The platform provides an extensive library of built-in functions and toolboxes, enabling users to
perform complex mathematical calculations and develop sophisticated models quickly. Its interactive
environment allows for easy experimentation and iteration, while its graphical capabilities facilitate
the creation of high-quality plots and visualizations. MATLAB is extensively used in academia,
research, and various industries for tasks ranging from simple calculations to large-scale simulations
and model-based design.
Understanding Matlab
Understanding MATLAB involves grasping both its core functionalities and its application potential.
At its foundation, MATLAB is a programming language designed for numerical and technical
computing. It is particularly powerful in handling and manipulating matrices, which are central to
many scientific and engineering problems.
Key features Matlab include:
Matrix and Array Computations
Extensive Function Library
Data Visualization and Plotting
Interactive Environment
Simulink Integration
Algorithm Development
Support for Multiple Programming Paradigms
App Designer and GUI Development
Parallel Computing
The Synergy of Matlab and Arduino
MATLAB can be used with Arduino to develop and test algorithms, control hardware, and acquire
data in real-time. This integration is facilitated by the MATLAB Support Package for Arduino, which
allows MATLAB to communicate directly with Arduino boards
Department of Electronics and Communication Engineering, NMIT-Bengaluru
7
Work Carried Out
1. Day 1: MATLAB Environment & Basics
MATLAB Interface Components:
Command Window: The Command Window is where you can enter individual commands or
expressions. It's interactive, meaning you can run commands and get immediate results. This is
often where you do quick calculations or run scripts.
Workspace: This area stores the variables that are currently in use. After defining variables in
the Command Window or running a script, they appear in the Workspace, where you can see
their values, dimensions, and types.
Current Folder Browser: This section shows the files in your current working directory.
MATLAB works with files like .m scripts and .mat data files. This is where you manage your
files, open them, and organize your project directories.
Editor: The Editor is used for writing and editing scripts (files with the .m extension). Scripts
allow you to save multiple lines of code and run them all at once, rather than typing each line
individually in the Command Window.
Command History: This window keeps a log of the commands you’ve entered in the
Command Window. You can re-run past commands by selecting them.
Figure Window: Whenever you plot a graph, MATLAB opens a Figure Window. It’s a
separate window where the plot is displayed. You can interact with your plots and save them
from this window.
Help Browser: MATLAB comes with extensive documentation, tutorials, and examples, all
accessible through the Help Browser.
2. Basics of MATLAB Programming:
2.1. Variables and Data Types:
Variable Assignment: In MATLAB, variables are created by simply assigning values to them:
x = 10;
y = 5.5;
z = 'Hello, MATLAB!';
Data Types: MATLAB supports various data types including:
o Numeric (integers, floating-point numbers)
o Character arrays (strings)
o Logical (boolean)
o Structures and cell arrays for grouping data.
2.2. Matrices and Arrays:
MATLAB is designed for working with matrices and arrays.
Matrix Creation:
A = [1, 2, 3; 4, 5, 6; 7, 8, 9]; % 3x3 matrix
B = [1, 2, 3]; % 1x3 vector
Department of Electronics and Communication Engineering, NMIT-Bengaluru
8
Array Indexing:
A(2, 3) % Access element at row 2, column 3
B(1:2) % Access the first two elements of vector B
2.3. Operations on Arrays:
MATLAB supports element-wise operations, matrix multiplication, and mathematical
functions
C = A + 2; % Add 2 to each element of A
D = A * B'; % Matrix multiplication
E = A .* A; % Element-wise multiplication
2.4. Basic Mathematical Functions:
MATLAB has a rich library of built-in functions for mathematical operations
sum(B) % Sum of elements in B
mean(A) % Mean of elements in matrix A
max(A) % Maximum value in matrix A
2.5. Scripts and Functions:
Scripts: A script is a file containing a sequence of MATLAB commands, saved with the
extension .m. You can create a script by opening the Editor and saving it with a name like
myscript.m. To run the script, just type the script name (without .m) in the Command Window:
% Example of a simple script
x = 5;
y = 10;
result = x * y;
disp(result)
Functions: MATLAB functions allow you to create reusable blocks of code. A function is also
stored in an .m file, but it starts with the function keyword:
function output = addNumbers(a, b)
output = a + b;
end
You can call this function by typing:
result = addNumbers(3, 4); % Calls the function and returns 7
3. Plotting and Visualization:
Visualization is one of MATLAB’s key strengths. You can create simple 2D and 3D plots
easily.
3.1. Basic 2D Plot:
x = 0:0.1:10;
y = sin(x);
Department of Electronics and Communication Engineering, NMIT-Bengaluru
9
plot(x, y) % Plots sine wave
xlabel('x-axis')
ylabel('y-axis')
title('Sine Wave')
grid on
3.2. Subplots:
You can create multiple plots in the same figure using subplots:
subplot(2, 1, 1); % Create a 2x1 grid of plots, and place this in the first row
plot(x, y)
title('First Plot')
subplot(2, 1, 2); % Place this in the second row
plot(x, cos(x))
title('Second Plot')
Department of Electronics and Communication Engineering, NMIT-Bengaluru
10
3.3. 3D Plot:
[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);
Z = X.^2 + Y.^2;
mesh(X, Y, Z)
xlabel('X-axis')
ylabel('Y-axis')
zlabel('Z-axis')
title('3D Plot Example')
4. Control Flow (Loops and Conditionals):
If-Else Statements:
if x > 10
disp('x is greater than 10')
elseif x == 10
disp('x is equal to 10')
else
disp('x is less than 10')
end
For Loop:
for i = 1:10
disp(i)
end
While Loop:
while x < 10
x = x + 1;
end
Department of Electronics and Communication Engineering, NMIT-Bengaluru
11
5. File I/O:
Loading and Saving Data: You can save and load variables to/from .mat files:
save('myData.mat', 'x', 'y'); % Save variables x and y to a .mat file
load('myData.mat'); % Load the variables back into the workspace
Reading from and Writing to Files: MATLAB can read/write to text or CSV files.
m
data = csvread('myFile.csv');
csvwrite('output.csv', data);
6. Toolboxes:
MATLAB has specialized toolboxes for different domains:
Signal Processing Toolbox for filtering and signal analysis.
Image Processing Toolbox for image manipulation and analysis.
Machine Learning Toolbox for implementing machine learning algorithms.
Department of Electronics and Communication Engineering, NMIT-Bengaluru
12
Day 2: Data Analysis and Visualization
Data analysis and visualization are core strengths of MATLAB, making it a popular tool for engineers,
scientists, and researchers. MATLAB provides robust functionalities for importing, exploring, analyzing, and
visualizing data. Below is a detailed overview of how to perform data analysis and visualization in
MATLAB.
1. Data Importing and Preprocessing
1.1. Importing Data
MATLAB allows you to import data from various sources such as text files, Excel, CSV, databases, and
more.
Text/CSV Files: You can use readtable, readmatrix, or readcell depending on the data format:
matlab
Copy code
data = readtable('myData.csv'); % Reads the file as a table
matrixData = readmatrix('myData.csv'); % Reads as a numeric matrix
Excel Files:
matlab
Copy code
data = readtable('myData.xlsx'); % Reads data from an Excel file
Databases: For databases, MATLAB’s Database Toolbox enables SQL-based importing.
matlab
Copy code
conn = database('myDatabase', 'username', 'password');
data = fetch(conn, 'SELECT * FROM myTable');
close(conn);
1.2. Cleaning Data
Once the data is loaded, it may need cleaning to handle missing or erroneous values:
Handling Missing Values:
matlab
Copy code
data = rmmissing(data); % Removes rows with missing values
data.Filled = fillmissing(data, 'linear'); % Fills missing values with linear interpolation
Removing Outliers:
matlab
Copy code
dataWithoutOutliers = rmoutliers(data); % Removes outliers from the dataset
1.3. Basic Data Exploration
After loading the data, it’s crucial to explore it to understand its structure and contents:
Summary Statistics:
matlab
Copy code
summary(data); % Provides a summary of the table, including mean, min, max
meanVal = mean(data.Var1); % Compute the mean of a specific variable
Sorting and Filtering:
matlab
Copy code
sortedData = sortrows(data, 'Var1'); % Sort data by 'Var1'
filteredData = data(data.Var1 > 10, :); % Filter rows where Var1 > 10
2. Data Analysis
2.1. Descriptive Statistics
MATLAB provides built-in functions for basic statistics:
Department of Electronics and Communication Engineering, NMIT-Bengaluru
13
Mean, Median, and Mode:
meanValue = mean(data.Var1); % Mean of a column
medianValue = median(data.Var1); % Median of a column
modeValue = mode(data.Var1); % Mode of a column
Standard Deviation and Variance:
matlab
Copy code
stdValue = std(data.Var1); % Standard deviation
varValue = var(data.Var1); % Variance
Correlation and Covariance:
matlab
Copy code
corrMatrix = corrcoef([data.Var1, data.Var2]); % Correlation between two variables
covMatrix = cov([data.Var1, data.Var2]); % Covariance matrix
2.2. Regression Analysis
MATLAB provides tools for both linear and nonlinear regression analysis:
Linear Regression:
matlab
Copy code
X = data.Var1; % Predictor variable
Y = data.Var2; % Response variable
model = fitlm(X, Y); % Fit a linear model
disp(model);
plot(model); % Plot the linear fit
Nonlinear Regression: For nonlinear regression, you can use fitnlm or custom functions:
matlab
Copy code
% Define a custom nonlinear function
modelfun = @(b,x) b(1)*exp(b(2)*x);
beta0 = [1, 1]; % Initial guesses for parameters
nlmodel = fitnlm(X, Y, modelfun, beta0);
disp(nlmodel);
2.3. Data Transformation
Normalization and Standardization:
matlab
Copy code
normalizedData = normalize(data.Var1); % Normalize the data between 0 and 1
standardizedData = (data.Var1 - mean(data.Var1)) / std(data.Var1); % Standardize data
Smoothing and Filtering: You can smooth data to remove noise, using methods like moving
average:
matlab
Copy code
smoothedData = smoothdata(data.Var1, 'movmean', 5); % Apply moving average smoothing
2.4. Fourier Transform for Signal Analysis
Fourier transforms are useful in analyzing signals and extracting frequency components:
matlab
Copy code
Department of Electronics and Communication Engineering, NMIT-Bengaluru
14
Y = fft(data.Var1); % Perform the Fourier transform
plot(abs(Y)); % Plot the magnitude of the frequency components
3. Data Visualization
3.1. Basic Plotting
MATLAB offers many options for plotting and visualizing data.
2D Line Plot:
matlab
Copy code
x = 1:10;
y = rand(1, 10);
plot(x, y);
xlabel('X-axis');
ylabel('Y-axis');
title('Random Data Plot');
grid on;
Scatter Plot: Scatter plots are useful for visualizing relationships between two variables.
matlab
Copy code
scatter(data.Var1, data.Var2);
xlabel('Var1');
ylabel('Var2');
title('Scatter Plot of Var1 vs Var2');
Bar Plot:
matlab
Copy code
bar(data.Var1);
xlabel('Categories');
ylabel('Values');
title('Bar Plot Example');
3.2. Statistical Plots
MATLAB offers specialized plots for statistical data analysis.
Histogram:
matlab
Copy code
histogram(data.Var1);
title('Histogram of Var1');
Box Plot: Box plots show the distribution of data.
matlab
Copy code
boxplot(data.Var1);
title('Box Plot of Var1');
QQ Plot (Quantile-Quantile): A QQ plot helps in checking if data follows a normal distribution.
matlab
Copy code
qqplot(data.Var1);
title('QQ Plot of Var1');
3.3. 3D Plots
For multi-dimensional data, MATLAB provides 3D plotting options.
Surface Plot:
matlab
Department of Electronics and Communication Engineering, NMIT-Bengaluru
15
Copy code
[X, Y] = meshgrid(1:10, 1:10);
Z = sin(X) .* cos(Y);
surf(X, Y, Z);
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('3D Surface Plot');
3D Scatter Plot:
matlab
Copy code
scatter3(data.Var1, data.Var2, data.Var3);
xlabel('Var1');
ylabel('Var2');
zlabel('Var3');
title('3D Scatter Plot');
3.4. Subplots
Subplots are useful when you want to display multiple plots in the same figure.
matlab
Copy code
subplot(2, 1, 1); % Create a subplot grid with 2 rows and 1 column, activate the first
plot(data.Var1);
title('Plot 1');
subplot(2, 1, 2); % Activate the second subplot
plot(data.Var2);
title('Plot 2');
3.5. Advanced Customization
MATLAB allows extensive customization of plots, including setting axes limits, adding legends, and
changing colors.
matlab
Copy code
plot(x, y, 'r--', 'LineWidth', 2); % Plot with red dashed line and line width of 2
xlim([0 10]); % Set x-axis limits
ylim([0 1]); % Set y-axis limits
legend({'Random Data'}, 'Location', 'northeast'); % Add a legend
3.6. Interactive Data Visualization
MATLAB offers interactive data exploration tools:
Data Cursor: Allow users to click on points in a plot to display their values.
matlab
Copy code
datacursormode on; % Activate data cursor mode
Interactive Plotting Apps: MATLAB provides apps like Curve Fitting and Data Explorer for interactive
data analysis and visualization.
4. Geospatial Data Visualization
MATLAB also supports visualization of geospatial data using maps:
Mapping Toolbox: Use functions to visualize data on maps, plot coordinates, and visualize geospatial
data.
matlab
Copy code
worldmap('World'); % Creates a world map
Department of Electronics and Communication Engineering, NMIT-Bengaluru
16
load coastlines;
plotm(coastlat, coastlon); % Plot coastlines on the map
5. Big Data and Live Data Visualization
5.1. Handling Big Data
MATLAB’s Tall Arrays and Datastores can handle datasets that don’t fit into memory.
Tall Arrays
Department of Electronics and Communication Engineering, NMIT-Bengaluru
17
Day 3: Simulink
MATLAB Simulink is a simulation and model-based design environment primarily used for dynamic
and embedded systems. It allows you to model, simulate, and analyze systems in an intuitive,
graphical way. Instead of writing lines of code, you create models by connecting blocks that represent
different parts of a system.
Here’s an overview of Simulink and its key features:
1. Introduction to Simulink
1.1. What is Simulink?
Simulink is an add-on product to MATLAB that provides an environment for:
Graphical Modeling: Simulink uses a block diagram approach, where each block represents a
component of the system, such as transfer functions, integrators, and mathematical operations.
Simulation: Simulink allows you to simulate systems to observe their time-domain responses.
Control Design and Analysis: Simulink is particularly useful in designing control systems
like PID controllers.
Code Generation: For real-time systems, Simulink can generate C/C++ code from models,
which can be deployed on hardware.
1.2. Applications of Simulink
Simulink is widely used in:
Control systems (e.g., PID control, state-space models)
Signal processing (e.g., digital filters, modulation)
Communication systems
Power systems
Mechanical systems (e.g., motors, robotics)
Embedded systems (using Simulink for hardware like microcontrollers, FPGAs)
2. Simulink Environment
When you open Simulink from MATLAB, you encounter its graphical user interface:
Library Browser: Contains predefined blocks that represent various operations or system
components. Blocks are organized into categories such as "Continuous," "Discrete," "Sinks,"
"Sources," etc.
Simulink Editor: The canvas where you build models by dragging and connecting blocks.
This is the heart of model creation.
3. Key Components of Simulink
3.1. Blocks
Simulink uses blocks as the fundamental components to represent different mathematical operations or
system components:
Sources: Provide input signals (e.g., constant, step, sine wave).
Sinks: Represent output or display (e.g., Scope, Display, To Workspace).
Math Operations: Represent basic mathematical functions (e.g., sum, product, gain).
Continuous and Discrete: For continuous-time (e.g., Integrator, Transfer Fcn) and discrete-
time (e.g., Discrete Filter, Unit Delay) systems.
3.2. Subsystems
A Subsystem is a grouping of blocks. It allows for hierarchical modeling, improving
readability, and managing complex systems.
You can create a Subsystem by selecting a group of blocks, right-clicking, and choosing
Department of Electronics and Communication Engineering, NMIT-Bengaluru
18
“Create Subsystem.”
3.3. Signals and Connections
Signals represent data that flows between blocks. You create connections between blocks by
drawing lines to represent signals.
Signals can be continuous (for continuous systems) or discrete (for discrete systems).
3.4. Scope and Visualization
The Scope block is used to visualize signals, allowing you to see how a signal changes over
time
scope = Simulink.SimulationData.logsout.get('SignalName');
plot(scope.Values.Time, scope.Values.Data);
4. Building a Model in Simulink
Here is a step-by-step guide for building a basic model in Simulink:
4.1. Creating a Simple Model: Second-Order System
1. Start Simulink:
This opens the Simulink start page where you can create a new model.
2. Add Components:
o Drag and drop the Integrator, Gain, and Sum blocks from the library.
o Add a Step input and a Scope block for output visualization.
3. Connect Components:
o Connect the blocks using lines. For a second-order system, connect two integrators in
series, apply feedback, and configure gain values.
o Connect the step input to the first block, and the last block (output) to the Scope.
4. Configure Blocks:
o Double-click the blocks to modify parameters such as gain values, step input time, or
initial conditions.
5. Run Simulation:
o Press the Run button to simulate the system.
o The Scope block will show the system's response to the input.
6. Analyze Results:
o Open the Scope to visualize the step response of the system.
o Adjust parameters as needed and rerun the simulation to observe different behaviors.
5. Simulation Parameters
5.1. Solver Configuration
The Solver is a key component in Simulink that controls the simulation step size and method
for solving differential equations.
MATLAB offers two types of solvers:
o Fixed-step: Good for real-time systems. The simulation step size is constant.
o Variable-step: The step size is adjusted based on the system's dynamics.
You can access these settings by going to Simulation > Model Configuration Parameters > Solver.
5.2. Simulation Time
Define how long the simulation should run (e.g., 0 to 10 seconds).
You can control simulation time via the Stop Time field in the Simulink editor or by using the
command:
simOut = sim('model_name', 'StopTime', '10');
Department of Electronics and Communication Engineering, NMIT-Bengaluru
19
6. Advanced Features in Simulink
6.1. Modeling Nonlinear Systems
Simulink can handle nonlinear systems through blocks like Saturation, Lookup Tables, and custom
MATLAB Function blocks.
Saturation Block: Limits the signal between a minimum and maximum value.
matlab
Copy code
add_block('simulink/Discontinuities/Saturation', 'myModel/Saturation');
MATLAB Function Block: Allows you to define custom functions in MATLAB and use
them in your Simulink model.
matlab
Copy code
function y = fcn(u)
y = u^2 + sin(u);
end
6.2. State-Space and Transfer Function Models
Simulink provides blocks for control system representation such as Transfer Function and State-
Space blocks.
Transfer Function Block: Define the transfer function by specifying the numerator and
denominator:
G = tf ([1], [1 2 1]); % Transfer function H(s) = 1 / (s^2 + 2s + 1)
State-Space Block: You can define state-space models by specifying matrices AAA, BBB,
CCC, and DDD.
A = [0 1; -2 -3]; B = [0; 1]; C = [1 0]; D = [0];
sys = ss(A, B, C, D);
6.3. Simulink Control Design
Simulink can be used to design and tune control systems. For example, you can implement and tune
PID controllers:
Use the PID Controller block and tune it with the PID Tuner tool.
pidtool % Opens the PID tuning tool
6.4. Signal Processing and Communication
Simulink supports advanced signal processing tasks like filtering, FFTs, modulation, and
demodulation. Use blocks from the Signal Processing and Communications System toolboxes.
6.5. Simscape for Physical Systems
Simscape is a Simulink add-on that enables the modeling of physical systems such as electrical,
mechanical, and hydraulic systems. It uses physical connections (rather than signal flows) to represent
interactions between components.
You can model a DC motor, a spring-mass system, or a hydraulic valve using Simscape
blocks.
7. Code Generation
Simulink provides a feature to generate C/C++ code from models for real-time implementation and
embedded systems.
Embedded Coder: Allows for C code generation that can be deployed to microcontrollers or
Department of Electronics and Communication Engineering, NMIT-Bengaluru
20
real-time targets.
rtwbuild('myModel'); % Build and generate code for the model
8. Co-Simulation with MATLAB and External Tools
8.1. Co-simulation with MATLAB
You can combine Simulink with MATLAB scripts for hybrid simulations. MATLAB scripts can be
used to run Simulink models, analyze results, or modify parameters dynamically.
matlab
Copy code
simOut = sim('myModel', 'StopTime', '20');
plot(simOut.logsout.get('signalName').Values.Time, simOut.logsout.get('signalName').Values.Data);
8.2. External Interfaces
Simulink also supports co-simulation with other software like Simulink Real-Time, LabVIEW, or
Modelica.
9. Optimization and Parameter Tuning
Simulink includes tools like Simulink Design Optimization that allow you to optimize parameters for
dynamic systems. You can tune parameters to meet design requirements such as response time,
overshoot, or stability margins
Department of Electronics and Communication Engineering, NMIT-Bengaluru
21
Day 5: Project Work and Final Presentation
Project 1: Real time Edge Detection
Edge detection is an important technique in image processing used to detect boundaries within images. A real-
time edge detection algorithm can be implemented in MATLAB using the Image Processing Toolbox along
with a live camera feed. The most common method is to use the Canny, Sobel, or Prewitt operators for edge
detection.
Here’s how to create a real-time edge detection program in MATLAB:
1. Step-by-Step Guide to Real-Time Edge Detection
1.1. Initialize the Webcam
First, set up the live video stream using MATLAB's built-in webcam function. If you don’t have a webcam, you
can use a recorded video.
1.2. Edge Detection Algorithm
We’ll use the Canny edge detection algorithm for this example, but you can replace it with other methods such
as Sobel, Prewitt, or custom filters.
1.3. Display the Edge-Detected Image
The video feed will be displayed in real-time, and edge detection will be applied to each frame.
2. MATLAB Code for Real-Time Edge Detection
matlab
Copy code
% Step 1: Initialize webcam
cam = webcam; % Connect to the first available webcam
% Step 2: Create a figure window for displaying video
hFig = figure('Name', 'Real-Time Edge Detection', 'NumberTitle', 'off');
hAxes = axes(hFig);
% Step 3: Loop to continuously capture frames and apply edge detection
while ishandle(hFig) % Continue until the figure window is closed
% Capture a frame from the webcam
frame = snapshot(cam);
% Convert the frame to grayscale (if it is a color image)
grayFrame = rgb2gray(frame);
% Apply Canny edge detection
edges = edge(grayFrame, 'Canny');
% Display the original frame and the edge-detected frame side by side
imshowpair(frame, edges, 'montage', 'Parent', hAxes);
% Pause to allow the display to refresh
pause(0.01);
Department of Electronics and Communication Engineering, NMIT-Bengaluru
22
end
% Step 4: Release the webcam when done
clear cam;
3. Explanation of the Code
1. Webcam Initialization:
o cam = webcam; initializes the webcam. If you have multiple cameras, you can specify the
camera index (e.g., cam = webcam(2);).
o You can adjust the camera resolution if needed: cam.Resolution = '640x480';.
2. Grayscale Conversion:
o grayFrame = rgb2gray(frame); converts the color image to grayscale, which is essential for
edge detection algorithms like Canny.
3. Edge Detection:
o edge(grayFrame, 'Canny'); applies the Canny edge detection algorithm to the grayscale image.
You can replace 'Canny' with 'Sobel', 'Prewitt', or other methods:
Sobel: edge(grayFrame, 'Sobel');
Prewitt: edge(grayFrame, 'Prewitt');
4. Real-Time Display:
o imshowpair(frame, edges, 'montage', 'Parent', hAxes); displays both the original and edge-
detected images side by side in the same figure.
5. Refresh Loop:
o The while loop continuously captures frames from the webcam and processes them until the
figure window is closed.
6. Cleanup:
o clear cam; releases the webcam once you close the figure window.
4. Additional Customization
4.1. Tuning Edge Detection Parameters
You can customize the sensitivity of the edge detection by modifying the second and third arguments of the
edge function for the Canny method:
matlab
Copy code
edges = edge(grayFrame, 'Canny', [0.1 0.3]); % Adjust thresholds for finer tuning
4.2. Adding Filters or Smoothing
Before edge detection, you can apply smoothing filters (like Gaussian) to reduce noise:
matlab
Copy code
smoothedFrame = imgaussfilt(grayFrame, 2); % Apply Gaussian smoothing with sigma=2
edges = edge(smoothedFrame, 'Canny');
4.3. Using Other Edge Detection Algorithms
You can experiment with different edge detection techniques, like Sobel, Prewitt, or Roberts:
matlab
Copy code
edges = edge(grayFrame, 'Sobel'); % Sobel operator
edges = edge(grayFrame, 'Prewitt'); % Prewitt operator
Department of Electronics and Communication Engineering, NMIT-Bengaluru
23
edges = edge(grayFrame, 'Roberts'); % Roberts operator
5. Running the Program
1. Copy the code into a new MATLAB script (e.g., realtime_edge_detection.m).
2. Run the script. It will open a window that shows the real-time video feed with edge detection applied.
3. To stop the program, simply close the figure window.
This MATLAB program uses the webcam to perform real-time edge detection, applying the Canny algorithm to
every frame and displaying the results live. You can easily modify the code to use other edge detection methods
or include pre-processing steps such as image smoothing or denoising to improve the quality of the edges.
Department of Electronics and Communication Engineering, NMIT-Bengaluru
24
Department of Electronics and Communication Engineering, NMIT-Bengaluru
25
Project 2-Modulation and Demodulation Techniques
Modulation and demodulation are essential processes in communication systems. Modulation is the
process of varying a carrier signal to transmit information, while demodulation is the reverse process
to retrieve the original information signal from the modulated carrier. MATLAB provides several
built-in functions to simulate and analyze modulation schemes, both analog and digital.
Here’s a summary of common modulation and demodulation techniques with suitable MATLAB
code for each.
1. Amplitude Modulation (AM)
Amplitude Modulation (AM) is a technique in which the amplitude of the carrier wave is varied in
accordance with the information signal.
MATLAB Code for AM Modulation and Demodulation
matlab
Copy code
% Parameters
fs = 1000; % Sampling frequency
t = 0:1/fs:1-1/fs; % Time vector
fc = 100; % Carrier frequency (Hz)
fm = 10; % Modulation frequency (Hz)
A = 1; % Amplitude of the carrier
m = 0.5; % Modulation index
% Message signal (information signal)
msg = cos(2*pi*fm*t); % Cosine wave as message signal
% Carrier signal
carrier = A*cos(2*pi*fc*t);
% Amplitude Modulation (AM)
am_signal = (1 + m*msg).*carrier;
% Plotting the signals
subplot(3,1,1);
plot(t, msg);
title('Message Signal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t, carrier);
title('Carrier Signal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,3);
plot(t, am_signal);
title('AM Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% Demodulation (envelope detection)
demod_signal = abs(hilbert(am_signal));
Department of Electronics and Communication Engineering, NMIT-Bengaluru
26
figure;
plot(t, demod_signal);
title('Demodulated Signal');
xlabel('Time (s)');
ylabel('Amplitude');
The AM signal is generated by varying the amplitude of the carrier signal according to the
message signal.
Hilbert transform is used to detect the envelope (demodulation) of the AM signal.
2. Frequency Modulation (FM)
In Frequency Modulation (FM), the frequency of the carrier wave is varied in accordance with the
message signal.
MATLAB Code for FM Modulation and Demodulation
matlab
Copy code
% Parameters
fs = 10000; % Sampling frequency
t = 0:1/fs:1-1/fs; % Time vector
fc = 100; % Carrier frequency (Hz)
fm = 5; % Frequency of message signal (Hz)
kf = 50; % Frequency deviation constant
% Message signal
msg = cos(2*pi*fm*t); % Cosine wave as message signal
% FM Modulation
fm_signal = cos(2*pi*fc*t + 2*pi*kf*cumsum(msg)/fs);
Department of Electronics and Communication Engineering, NMIT-Bengaluru
27
% Plotting the signals
subplot(3,1,1);
plot(t, msg);
title('Message Signal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t, fm_signal);
title('FM Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% FM Demodulation (Differentiation and Hilbert transform)
demod_signal = diff(unwrap(angle(hilbert(fm_signal)))); % Differentiating phase
subplot(3,1,3);
plot(t(1:end-1), demod_signal);
title('Demodulated FM Signal');
xlabel('Time (s)');
ylabel('Amplitude');
Department of Electronics and Communication Engineering, NMIT-Bengaluru
28
3. Phase Modulation (PM)
In Phase Modulation (PM), the phase of the carrier wave is varied according to the amplitude of the
message signal.
MATLAB Code for PM Modulation and Demodulation
matlab
Copy code
% Parameters
fs = 10000; % Sampling frequency
t = 0:1/fs:1-1/fs; % Time vector
fc = 100; % Carrier frequency (Hz)
fm = 5; % Frequency of message signal (Hz)
kp = pi/4; % Phase deviation constant
% Message signal
msg = cos(2*pi*fm*t); % Cosine wave as message signal
% PM Modulation
pm_signal = cos(2*pi*fc*t + kp*msg);
% Plotting the signals
subplot(3,1,1);
plot(t, msg);
title('Message Signal');
xlabel('Time (s)');
ylabel('Amplitude');
subplot(3,1,2);
plot(t, pm_signal);
title('PM Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% PM Demodulation (using phase detector)
demod_signal = diff(unwrap(angle(pm_signal)));
subplot(3,1,3);
plot(t(1:end-1), demod_signal);
title('Demodulated PM Signal');
xlabel('Time (s)');
ylabel('Amplitude');
Department of Electronics and Communication Engineering, NMIT-Bengaluru
29
4. Digital Modulation: Binary Phase Shift Keying (BPSK)
Binary Phase Shift Keying (BPSK) is a digital modulation technique in which the phase of the carrier
signal is shifted according to the digital data.
MATLAB Code for BPSK Modulation and Demodulation
matlab
Copy code
% Parameters
N = 1000; % Number of bits
fc = 10; % Carrier frequency
fs = 100; % Sampling frequency
t = (0:N-1)/fs; % Time vector
% Generate random binary data
data = randi([0 1], 1, N);
% BPSK Modulation
bpsk_signal = cos(2*pi*fc*t + pi*data); % Phase shift by pi for bit '1'
% Plotting the signals
subplot(2,1,1);
stem(data(1:20));
title('Input Binary Data (First 20 bits)');
xlabel('Bit index');
ylabel('Amplitude');
subplot(2,1,2);
plot(t(1:200), bpsk_signal(1:200)); % Plot first few samples
title('BPSK Modulated Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% BPSK Demodulation (Coherent)
demod_signal = bpsk_signal .* cos(2*pi*fc*t); % Multiply with carrier
demod_signal = lowpass(demod_signal, fc, fs); % Low-pass filter to extract message
% Decision-making: Compare with zero to decode bits
received_data = demod_signal > 0;
figure;
stem(received_data(1:20));
title('Demodulated Binary Data (First 20 bits)');
xlabel('Bit index');
ylabel('Amplitude');
Department of Electronics and Communication Engineering, NMIT-Bengaluru
30
5. Quadrature Amplitude Modulation (QAM)
Quadrature Amplitude Modulation (QAM) is a combination of both amplitude and phase modulation.
It modulates both the amplitude and the phase of the carrier signal.
MATLAB Code for QAM Modulation and Demodulation
matlab
Copy code
% Parameters
M = 16; % 16-QAM
k = log2(M); % Number of bits per symbol
N = 1000; % Number of bits
fs = 100; % Sampling frequency
% Generate random binary data
data = randi([0 1], N, 1);
% Reshape binary data into symbols (groups of k bits)
symbols = reshape(data, length(data)/k, k);
% Convert binary to decimal symbols
decimal_symbols = bi2de(symbols);
% 16-QAM Modulation
qam_mod = qammod(decimal_symbols, M);
% Plotting the constellation diagram
scatterplot(qam_mod);
title('16-QAM Constellation Diagram');
% 16-QAM Demodulation
qam_demod = qamdemod(qam_mod, M);
% Convert demodulated symbols back to binary
received_bits = de2bi(qam_demod, k);
received_bits = received_bits(:); % Reshape into original bit stream
% Calculate Bit Error Rate (BER)
ber = sum(data ~= received_bits) / N;
fprintf('Bit Error Rate (BER): %f\n', ber);
Department of Electronics and Communication Engineering, NMIT-Bengaluru
31
CONCLUSION
Over the past five days, participants have gained hands-on experience with MATLAB, mastering both
fundamental and advanced concepts. The workshop covered a wide range of topics that highlighted
MATLAB’s role in technical computing, data analysis, and engineering simulations. Here’s a brief
summary of what was achieved:
1. Day 1: Introduction to MATLAB Environment and Basics
o Participants were introduced to the MATLAB interface, workspace, and key features.
Essential commands for performing basic arithmetic, array manipulations, and creating
functions were demonstrated. This built a strong foundation for MATLAB
programming.
Department of Electronics and Communication Engineering, NMIT-Bengaluru
32
2. Day 2: Data Analysis and Visualization
o The focus was on working with real-world data, processing it efficiently using
MATLAB’s built-in functions. Techniques for creating meaningful plots, graphs, and
visual representations were explored. Participants learned to analyze data using
statistical tools and to present results clearly.
3. Day 3: Advanced Programming Techniques
o Participants were exposed to more complex programming concepts, including control
flow, custom function creation, file I/O operations, and error handling. Object-oriented
programming (OOP) was introduced, giving a deeper understanding of MATLAB’s
programming capabilities.
4. Day 4: Simulink and Model-Based Design
o Simulink, MATLAB’s block diagram-based simulation environment, was explored.
Participants learned how to model, simulate, and analyze dynamic systems, from
simple mechanical systems to complex control systems. This practical exposure to
simulation enhanced their understanding of real-world applications.
5. Day 5: Real-Time Applications and Communication Systems
o The final day delved into real-time applications, focusing on signal processing,
modulation/demodulation techniques, and image processing. Participants worked on
live projects such as edge detection, modulation, and demodulation, applying what they
learned throughout the week.
Key Takeaways
Hands-on Practice: Through numerous examples and exercises, participants strengthened their
programming and simulation skills, enabling them to tackle engineering and data science
problems effectively.
Collaboration and Knowledge Sharing: The workshop fostered collaboration, encouraging
participants to share ideas and discuss various approaches to problem-solving.
Real-World Application: By the end of the workshop, participants gained the confidence to
apply MATLAB in real-world scenarios, whether in academic research, industry projects, or
personal development.
Overall, this workshop has equipped participants with a solid foundation in MATLAB, enabling them
to continue learning and exploring more advanced topics. With MATLAB’s extensive applications,
they are now well-prepared to leverage its power in their respective fields.
Department of Electronics and Communication Engineering, NMIT-Bengaluru
33
REFERENCE
1. MathWorks. (2023). MATLAB Documentation. The MathWorks, Inc. Available at:
https://www.mathworks.com/help/matlab/
2. MathWorks. (2023). Simulink Documentation. The MathWorks, Inc. Available at:
https://www.mathworks.com/help/simulink/
3. Attaway, S. (2020). MATLAB: A Practical Introduction to Programming and Problem
Solving. 5th Edition. Butterworth-Heinemann.
4. Zhao, H., & Zhang, S. (2018). "A Novel Real-Time Edge Detection Algorithm Using
MATLAB." Journal of Image Processing, 12(3), 123-135.
5. MathWorks. (2023). Signal Processing Toolbox. The MathWorks, Inc. Available at:
https://www.mathworks.com/products/signal.html
6. MathWorks. (2023). MATLAB Onramp. The MathWorks, Inc. Available at:
https://matlabacademy.mathworks.com/
7. Author Name (Year). Function Name. MATLAB Central File Exchange. Available at:
https://www.mathworks.com/matlabcentral/fileexchange/xxxxx
Department of Electronics and Communication Engineering, NMIT-Bengaluru
34