0% found this document useful (0 votes)
0 views

Engineering With MATLAB

The document is a handbook titled 'Engineering With MATLAB: A Hands-on Introduction' authored by Dr. Jagadish Tawade and Nitiraj Kulkarni, covering fundamental concepts and applications of MATLAB. It includes sections on installation, basic commands, data visualization, and specific applications in engineering and finance. The handbook aims to provide a comprehensive guide for users to effectively utilize MATLAB for numerical computing and modeling.

Uploaded by

raedhasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Engineering With MATLAB

The document is a handbook titled 'Engineering With MATLAB: A Hands-on Introduction' authored by Dr. Jagadish Tawade and Nitiraj Kulkarni, covering fundamental concepts and applications of MATLAB. It includes sections on installation, basic commands, data visualization, and specific applications in engineering and finance. The handbook aims to provide a comprehensive guide for users to effectively utilize MATLAB for numerical computing and modeling.

Uploaded by

raedhasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

Handbook

Engineering With
MATLAB: A Hands-
on Introduction

Dr. Jagadish Tawade


Nitiraj Kulkarni
Title: Engineering With MATLAB: A Hands-on Introduction
Authors: Dr. Jagadish Tawade & Nitiraj Kulkarni.
Copyright © 2024 Dr. Jagadish Tawade & Nitiraj Kulkarni.
No part of this publication may be reproduced, stored in a
retrieval system, or transmitted, in any form or by any means,
without the prior permission in writing of the publisher, nor be
otherwise circulated in any form of binding or cover other than
that in which it is published and without a similar condition
including this condition being imposed on the subsequent
purchaser.
All rights reserved.
Publisher: Self Published
DEDICATED TO
Our Parents & Cats
CONTENTS

1 Introduction to MATLAB 07
2 Basic Commands and Operations 21
3 Vectors and Matrices 41
4 Programming in MATLAB 56
5 Data Visualization in MATLAB 75
6 Working with Data 98
7 Toolboxes and Applications 120
8 Debugging and Troubleshooting 153
9 Introduction to Simulink 160
10 Simulating Simulink Models 170
CHAPTER 1

INTRODUCTION TO
MATLAB

What is MATLAB?
MATLAB, which stands for Matrix Laboratory, is a
high-level programming environment specifically
designed for numerical computing. Created by
MathWorks, MATLAB provides a comprehensive
environment for engineers, scientists, and anyone
who needs to perform complex numerical
computations, analyze large data sets, or create
sophisticated models. Unlike many other
programming languages that require extensive
knowledge of coding syntax and concepts, MATLAB
allows users to solve technical computing problems
more efficiently with a simple and intuitive language.
At its core, MATLAB is designed to handle matrices
and arrays, which makes it exceptionally powerful for
linear algebra and matrix computations. This is
particularly beneficial in various scientific and
engineering disciplines where such operations are
7
Engineering with MATLAB: A Hands-on Introduction

commonplace. Additionally, MATLAB integrates


computation, visualization, and programming in an
easy-to-use environment where problems and
solutions are expressed in familiar mathematical
notation. This integration helps users see their data
and algorithms at work, providing immediate visual
feedback and insights.
The language's high-level commands enable users to
perform complex tasks, such as data analysis,
algorithm development, and modeling, without
needing to write extensive lines of code. MATLAB
also includes an extensive library of built-in functions
for tasks such as signal processing, image processing,
and control systems, which significantly enhances
productivity.

History and Evolution


MATLAB's journey began in the late 1970s when
Cleve Moler, a mathematics and computer science
professor at the University of New Mexico, created it
as a tool for his students. Moler wanted his students
to have easy access to LINPACK and EISPACK
without digging into Fortran, the standard
programming language for numerical computations
at the time. He envisioned a more user-friendly
environment where students could focus on learning
numerical analysis rather than struggling with
8
Engineering with MATLAB: A Hands-on Introduction

programming syntax.
In the early 1980s, Jack Little and Steve Bangert
recognized the potential of Moler's work and joined
forces with him to commercialize MATLAB. In 1984,
they founded MathWorks and released the first
commercial version of MATLAB. This marked the
beginning of MATLAB's evolution from a simple
educational tool to a powerful and versatile
computing environment.
Over the years, MATLAB has undergone significant
enhancements and expansions. The introduction of
the first graphical user interface (GUI) in MATLAB
4.0 in the early 1990s revolutionized how users
interacted with the software. This update made it
easier for users to visualize data and results, paving
the way for more widespread adoption.
As the computing landscape evolved, so did
MATLAB. The addition of Simulink in the mid-1990s
brought a new dimension to MATLAB, allowing users
to model, simulate, and analyze dynamic systems
graphically. This capability was particularly useful in
control systems, signal processing, and
communication systems, making MATLAB an
indispensable tool in these fields.
In the 2000s and beyond, MATLAB expanded its
capabilities further with the introduction of toolboxes
for specialized applications such as machine learning,
9
Engineering with MATLAB: A Hands-on Introduction

parallel computing, and deep learning. These


toolboxes provided pre-built functions and tools
tailored to specific domains, enabling users to solve
complex problems more efficiently.

Applications and Use Cases


MATLAB's versatility makes it suitable for a wide
range of applications across various industries and
disciplines. Its ability to handle complex numerical
computations, data analysis, and visualization makes
it a go-to tool for engineers, scientists, financial
analysts, and researchers.
In engineering, MATLAB is extensively used for tasks
such as signal processing, control systems design, and
image processing. For instance, in signal processing,
MATLAB allows engineers to analyze and filter
signals, design digital filters, and perform Fourier
analysis. These capabilities are crucial in
telecommunications, audio engineering, and medical
diagnostics.
Control systems engineers use MATLAB to model
and simulate control systems for automation,
robotics, and aerospace applications. By using
Simulink, a companion product to MATLAB,
engineers can create block diagrams of their systems
and simulate their behavior under different
conditions. This helps in designing controllers and
10
Engineering with MATLAB: A Hands-on Introduction

understanding the system dynamics before


implementing them in real-world scenarios.
In image processing, MATLAB provides tools for
reading, writing, and manipulating images.
Researchers and engineers use MATLAB to enhance
image quality, detect objects, and analyze patterns.
This is particularly useful in fields such as medical
imaging, where MATLAB is used to process and
analyze MRI and CT scans.
The financial industry also benefits from MATLAB's
capabilities. Quantitative analysts use MATLAB for
developing and testing algorithms for risk
management, derivative pricing, and portfolio
optimization. MATLAB's ability to handle large
datasets and perform complex calculations makes it
ideal for financial modeling and analysis.
Additionally, MATLAB is used in algorithmic trading
to create and backtest trading strategies using
historical market data.
In academia, MATLAB serves as both a teaching tool
and a research aid. Professors use MATLAB to teach
numerical methods, linear algebra, and other
mathematical concepts. The interactive environment
helps students understand complex topics through
hands-on experimentation and visualization.
Researchers use MATLAB to perform numerical
simulations, analyze experimental data, and
11
Engineering with MATLAB: A Hands-on Introduction

prototype new algorithms. Data scientists and


machine learning engineers leverage MATLAB for
data analysis, visualization, and machine learning.
MATLAB's machine learning toolbox provides
functions for classification, regression, clustering, and
more. It also includes tools for feature extraction,
model validation, and performance evaluation,
making it a comprehensive environment for
developing and deploying machine learning models.

Getting Started with MATLAB


Installation and Setup
To start using MATLAB, you first need to install it on
your computer. The installation process is
straightforward, but it is important to ensure that
your system meets the minimum requirements
specified by MathWorks.

1. System Requirements:
• Ensure your system meets the minimum
requirements specified by MathWorks. These
typically include specifications for the
operating system, RAM, and disk space.

12
Engineering with MATLAB: A Hands-on Introduction

2. Downloading MATLAB:
• Visit the MathWorks website and log in or
create a MathWorks account.

• Navigate to the Downloads section and select


the appropriate version for your operating
system.

3. Installation Guide:
• Run the installer and follow the on-screen
instructions. You will need to enter your
MathWorks account credentials and select the
products and toolboxes you wish to install.

13
Engineering with MATLAB: A Hands-on Introduction

4. Setting Up the MATLAB Environment:


• After installation, launch MATLAB. The first
time you open it, you may need to activate
your license by logging in to your MathWorks
account.
• Configure your MATLAB environment by
setting preferences such as default folder paths,
font sizes, and display options.

MATLAB Interface Overview


When you open MATLAB, you will see the main
interface, which consists of several key components.
Understanding these components will help you
navigate MATLAB more effectively and make the
most of its features.
14
Engineering with MATLAB: A Hands-on Introduction

The Command Window is the primary area where


you can enter commands and execute MATLAB code
interactively. Here, you can perform calculations,
define variables, and run scripts. The Command
Window provides immediate feedback, displaying
the results of your commands as soon as you enter
them.
The Workspace displays the variables you create and
their current values. It provides a quick overview of
the data you are working with and allows you to
manage these variables easily. You can double-click
on a variable in the Workspace to open it in the
Variable Editor, where you can view and edit its
contents.
The Command History keeps a record of the
commands you have entered in the Command
Window. This feature is useful for reviewing your
previous commands and reusing them without
having to retype them. You can also save a sequence
of commands from the Command History as a script
for future use.
The Current Folder shows the files and folders in the
current directory. This component helps you manage
your MATLAB files and navigate your project
directories. You can open, rename, and delete files
directly from the Current Folder.
The Editor is where you can write, edit, and save
15
Engineering with MATLAB: A Hands-on Introduction

MATLAB scripts and functions. The Editor provides


features such as syntax highlighting, code folding,
and debugging tools to help you write and maintain
your code more efficiently. You can open multiple
scripts and functions in separate tabs within the
Editor, making it easy to switch between different
pieces of code.

16
Engineering with MATLAB: A Hands-on Introduction

Important MATLAB Shortcuts:

General Shortcuts used in MATLAB


Windows/
Mac
Category Action Linux
Shortcut
Shortcut
Open
Command +
Command Ctrl + 0
0
Window
Ctrl + Shift + Command +
Open Editor
E Shift + E
Open Ctrl + Shift + Command +
Workspace W Shift + W
Open
Ctrl + Shift + Command +
Current
D Shift + D
Folder
Open
General Ctrl + Shift + Command +
Command
Shortcuts H Shift + H
History
Run Current
F5 F5
Script
Save Current Command +
Ctrl + S
Script S
Command +
Open File Ctrl + O O

Close
Command +
Current Ctrl + W
W
Window

17
Engineering with MATLAB: A Hands-on Introduction

Editor Shortcuts used in MATLAB


Windows/
Mac
Category Action Linux
Shortcut
Shortcut
Comment
Command +
Selected Ctrl + R
R
Lines
Uncomment
Command +
Selected Ctrl + T
T
Lines
Indent
Selected Tab Tab
Lines
Unindent
Editor Selected Shift + Tab Shift + Tab

Shortcuts Lines
Command +
Find Ctrl + F
F
Command +
Replace Ctrl + H
H
Command +
Go to Line Ctrl + G
G
Toggle
F12 F12
Breakpoint
Navigate to Ctrl + Down Command +
Next Section Arrow Down Arrow

18
Engineering with MATLAB: A Hands-on Introduction

Command Window Shortcuts used in MATLAB


Windows/
Mac
Category Action Linux
Shortcut
Shortcut
Clear Command Command
Ctrl + L
Window +L
Recall Previous
Up Arrow Up Arrow
Command
Recall Next Down
Down Arrow
Command Arrow
Auto-complete
Function/Variable Tab Tab
Command Name
Window Command
Abort Command Ctrl + C
Shortcuts +C
Command
Copy Selection Ctrl + C
+C
Command
Paste Selection Ctrl + V
+V
Command
Select All Ctrl + A
+A
Clear All Ctrl + Shift + Command
Variables C + Shift + C

19
Engineering with MATLAB: A Hands-on Introduction

Editor and Debugging Shortcuts used in MATLAB


Windows/
Mac
Category Action Linux
Shortcut
Shortcut
New Ctrl + N Command
Script +N
Editor New Ctrl + Shift Command
Shortcuts Function +N + Shift + N
Save As Ctrl + Shift Command
+S + Shift + S
Step In F11 F11
Step Out Shift + F11 Shift + F11
Step Over F10 F10
Continue F5 F5
Debugging Execution
Shortcuts Pause Ctrl + F5 Command
Execution + F5
Exit Shift + F5 Shift + F5
Debug
Mode

These shortcuts enable us to efficiently manage all


aspects of MATLAB software, making navigation
smooth and intuitive.

20
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 2

BASIC COMMANDS
AND OPERATIONS

Understanding MATLAB syntax and commands


is foundational to using the software effectively.
MATLAB commands are executed in the Command
Window, and scripts or functions are written and run
through the Editor. The language's syntax is
straightforward and designed to facilitate matrix and
array operations, making it particularly useful for
engineering and scientific applications.

Before diving into specific commands and


operations, it's helpful to introduce some of the basic
symbols and conventions used in MATLAB. These
symbols are integral to writing and understanding
MATLAB code.

21
Engineering with MATLAB: A Hands-on Introduction

Symbol Description Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
Left division
(solving
\ A\b
systems of
equations)
Element-wise
.^ A .^ 2
power
Element-wise
.* A .* B
multiplication
Element-wise
./ A ./ B
division
= Assignment a=5
Colon operator
(creating
: 1:10
vectors, array
slicing)
End of
statement, row
; a = [1; 2; 3]
separator in
matrices
[] Array brackets A = [1, 2, 3]
() Parentheses sin(pi/4)

22
Engineering with MATLAB: A Hands-on Introduction

(grouping,
function
arguments)
Line a = 1 + 2 + ... \n
...
continuation 3+4
% This is a
% Comment
comment
Cell mode
%% (breaks scripts %% Section 1
into sections)

At its core, MATLAB can handle simple


arithmetic operations, making it easy to perform
calculations without the need for additional tools.

a = 10;
b = 5;
% Addition
sum = a + b; % sum = 15
% Subtraction
difference = a - b; % difference = 5
% Multiplication
product = a * b; % product = 50
% Division
quotient = a / b; % quotient = 2
% Modulus
remainder = mod(a, b); % remainder = 0
23
Engineering with MATLAB: A Hands-on Introduction

In these examples, a and b are variables that store


numerical values. The operations are performed
using standard arithmetic symbols. MATLAB
immediately provides the results, making it easy to
verify calculations.
Explanation of the code:
1. Addition (+): This operation adds two numbers
together. For example, 10 + 5 equals 15.
2. Subtraction (-): This operation subtracts one
number from another. For example, 10 - 5
equals 5.
3. Multiplication (*): This operation multiplies
two numbers. For example, 10 * 5 equals 50.
4. Division (/): This operation divides one
number by another. For example, 10 / 5 equals
2.
5. Modulus (mod): This operation finds
the remainder after division. For example,
mod(10, 5) equals 0.
Result:

24
Engineering with MATLAB: A Hands-on Introduction

Matrix Operations
One of MATLAB’s strengths is its ability to handle
matrices and arrays. This is particularly useful in
fields like engineering, physics, and mathematics
where matrix operations are frequent.

Matrix Addition and Subtraction


Matrix addition and subtraction are
straightforward in MATLAB. Each corresponding
element is added or subtracted.

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

In matrix addition and subtraction, the


corresponding elements of the matrices are added or
subtracted from each other. For example, for
matrices A and B as given, C = A + B results in a matrix
where each element is the sum of the corresponding
elements in A and B.
Result:

25
Engineering with MATLAB: A Hands-on Introduction

Matrix Multiplication
Matrix multiplication follows the rules of linear
algebra. It is different from element-wise
multiplication, as it involves the dot product of rows
and columns.

E = A * B; % Matrix multiplication

In matrix multiplication, the element at the i-th


row and j-th column of the product matrix is the dot
product of the i-th row of the first matrix and the j-th
column of the second matrix.
Result:

Element-wise Operations
For element-wise operations, where operations
are performed on corresponding elements of
matrices, use a dot before the operator:

F = A .* B; % Element-wise multiplication
G = A ./ B; % Element-wise division
H = A .^ 2; % Element-wise power
Element-wise operations are performed by
adding a dot (.) before the operator. This ensures that
26
Engineering with MATLAB: A Hands-on Introduction

the operation is applied to each corresponding


element individually rather than performing a matrix
operation.

Result:

Transpose of a Matrix
Transposing a matrix is simply swapping its rows
and columns:

transpose_A = A'; % Transpose of a matrix

Result:

Transposing a matrix involves flipping it over its


diagonal, turning its rows into columns and vice
versa.

27
Engineering with MATLAB: A Hands-on Introduction

Trigonometric Functions
MATLAB includes a comprehensive suite of
trigonometric functions. These are essential for
applications in engineering, physics, and other
sciences.
Understanding trigonometric functions in
MATLAB is crucial for solving problems related to
waves, oscillations, and rotations.

theta = pi / 4;
sin_theta = sin(theta); % sine of pi/4
cos_theta = cos(theta); % cosine of pi/4
tan_theta = tan(theta); % tangent of pi/4

Result:

These functions take angles in radians. To


convert degrees to radians, use the deg2rad function:

theta_deg = 45;
theta_rad = deg2rad(theta_deg);
sin_theta_deg = sin(theta_rad); % sine 45

28
Engineering with MATLAB: A Hands-on Introduction

Result:

Variables and Data Types


Variables in MATLAB are used to store data that
can be manipulated and processed. Understanding
data types and how to manage variables is crucial for
efficient programming.
Understanding trigonometric functions in
MATLAB is crucial for solving problems related to
waves, oscillations, and rotations.

x = 42;
name = 'John Doe';
is_student = true;

In this example, x is a numeric variable, name is a


string, and is_student is a logical variable.
Variables in MATLAB do not need explicit
declaration. You assign a value to a variable using the
equals sign (=), and MATLAB automatically
determines the appropriate data type.

29
Engineering with MATLAB: A Hands-on Introduction

MATLAB supports various data types, including:


• Numeric Types: double, single, int8, int16, int32,
int64, uint8, uint16, uint32, uint64
• Character and String Types: char, string
• Logical Type: logical
• Cell Arrays and Structures

% Numeric
num = 3.14; % double
num_int = int32(10);% 32-bit integer
% String
str = "Hello, MATLAB"; % string
% Logical
is_true = true; % logical
% Cell Array
cell_arr = {1, 'text', [2, 3, 4]}; % mixed
data types
% Structure
person.name = 'John';
person.age = 30;
Result:

30
Engineering with MATLAB: A Hands-on Introduction

Numeric types can store various forms of


numerical data. For example, double is the default
numeric type and can represent floating-point
numbers. int32 and other integer types can store
whole numbers, with different storage requirements
and ranges.
Character and string types are used for text data.
The char type is used for single characters or arrays
of characters, while the string type is used for text
data and provides more functionality.
Logical types are used to represent boolean values
(true or false).
Cell arrays and structures allow for more
complex data organization. Cell arrays can store data
of varying types and sizes, while structures can group
related data under a single variable.
Understanding and using these data types
effectively allows you to write versatile and robust
MATLAB programs.

31
Engineering with MATLAB: A Hands-on Introduction

Managing Workspace Variables


The workspace is where MATLAB stores
variables you create during a session. Managing these
variables efficiently is key to maintaining an
organized workspace.
You can view the current variables in the
workspace using the whos command:

The whos command is a powerful tool to keep


track of the variables you are working with. It
provides a quick overview of the variables’ properties,
which can help in debugging and optimizing your
code. To clear variables from the workspace, use the
clear command. Clearing variables is an important
step in avoiding conflicts and ensuring that outdated
data does not interfere with new calculations.

32
Engineering with MATLAB: A Hands-on Introduction

Built-in Functions
MATLAB is renowned for its extensive library of
built-in functions that cover a wide range of
operations from simple arithmetic to complex
mathematical computations, data analysis, and
graphical visualization. These functions are designed
to save time and effort by providing pre-written and
optimized code for common tasks. Understanding
and utilizing these built-in functions can greatly
enhance your productivity and efficiency when
working with MATLAB.
Built-in functions in MATLAB are predefined
functions that come with the software. These
functions are optimized for performance and are
thoroughly tested for accuracy. They cover various
domains including:
• Mathematics: Functions for numerical
computations, linear algebra, calculus, and
more.
• Statistics and Machine Learning: Functions
for statistical analysis, probability
distributions, regression, classification,
clustering, and machine learning.
• Signal Processing: Functions for filtering,
Fourier transforms, signal analysis, and more.
• Image Processing: Functions for image
analysis, enhancement, filtering, and
33
Engineering with MATLAB: A Hands-on Introduction

transformation.
• Optimization: Functions for finding minima
and maxima, linear and nonlinear
optimization.
• File I/O: Functions for reading from and
writing to files, handling various file formats.
• Graphics: Functions for plotting and
visualizing data in 2D and 3D.
Each of these categories includes numerous
functions tailored to specific tasks. MATLAB’s
documentation provides detailed descriptions and
examples for each function, making it easier to
understand their usage.

List Of Functions In Tabular Form On The Next


Page

34
Engineering with MATLAB: A Hands-on Introduction

List of Commonly used functions:


Function
Category Description
Name
Sum of array
sum
elements
Mean of array
mean
elements
Standard
std
Mathematical deviation
Functions Maximum
max
value
Minimum
min
value
abs Absolute value
sqrt Square root

Function
Category Description
Name
sin Sine function
Cosine
cos
function
Trigonometric Tangent
tan
Functions function
Inverse sine
asin
function
acos Inverse cosine

35
Engineering with MATLAB: A Hands-on Introduction

function
Inverse tangent
atan
function

Function
Category Description
Name
normpdf Normal
probability
density
function
normcdf Normal
cumulative
distribution
function
Statistical
binopdf Binomial
Functions
probability
density
function
binocdf Binomial
cumulative
distribution
function
median Median value

36
Engineering with MATLAB: A Hands-on Introduction

Function
Category Description
Name
inv Inverse of a
matrix
det Determinant
of a matrix
eig Eigenvalues
Matrix
and
Functions
eigenvectors
rank Rank of a
matrix
transpose Transpose of a
matrix

Function
Category Description
Name
Test if all
all elements are
true
Test if any
any
Logical element is true
Functions Find indices of
find nonzero
elements
Convert
logical
numeric values

37
Engineering with MATLAB: A Hands-on Introduction

to logical value
Function
Category Description
Name
Open file for
fopen reading or
writing
Close an open
fclose
file
Read binary
fread
data from a file
File I/O
Write binary
Functions fwrite
data to a file
Write
fprintf formatted data
to a file
Read
fscanf formatted data
from a file

Function
Category Description
Name
Create a 2D
plot
line plot
Plotting
Create a scatter
Functions scatter
plot
bar Create a bar

38
Engineering with MATLAB: A Hands-on Introduction

graph
Create a
hist
histogram
Create
multiple plots
subplot
in a single
figure

Function
Category Description
Name
Find
minimum of a
fminbnd
function of
one variable
Optimization Find
Functions minimum of
an
fminsearch
unconstrained
multivariable
function

Function
Category Description
Name
Current date
Date and Time now
and time
Functions
date Current date
39
Engineering with MATLAB: A Hands-on Introduction

as a string
Current date
clock and time as a
date vector
etime Elapsed time
Current date
now
and time

Function
Category Description
Name
strcmp Compare two
strings
strcat Concatenate
strings
strfind Find substring
String
within a string
Functions
sprintf Write
formatted data
to a string
str2num Convert string
to number
This table and detailed descriptions provide a
comprehensive overview of commonly used built-in
functions in MATLAB. Each function is accompanied
by an example to illustrate its usage, helping you to
understand how to apply these functions in your own
work.
40
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 3

VECTOR AND
MATRICES

In MATLAB, vectors and matrices are the


primary data structures used for numerical
computing and data manipulation. A vector is a one-
dimensional array of numbers, and it can be either a
row vector or a column vector. A matrix, on the other
hand, is a two-dimensional array of numbers
arranged in rows and columns. These structures are
pivotal for representing data, performing
mathematical computations, and solving systems of
equations in various fields such as engineering,
physics, computer science, and economics.
Vectors and matrices serve as the foundation for
linear algebra, which is the branch of mathematics
concerned with vector spaces and linear mappings
between these spaces. Understanding how to create,
manipulate, and utilize vectors and matrices in
MATLAB is essential for harnessing its computational
power.

41
Engineering with MATLAB: A Hands-on Introduction

Creating and Manipulating Vectors


Vectors in MATLAB can be created in several
ways. A row vector is created by enclosing a sequence
of numbers within square brackets and separating
them with spaces or commas. For example,
row_vector = [1, 2, 3, 4, 5];
A column vector is created similarly, but the
numbers are separated by semicolons:
column_vector = [1; 2; 3; 4; 5];

Once vectors are created, various operations can


be performed on them. Element-wise addition,
subtraction, multiplication, and division are
fundamental operations. Consider the following two
row vectors:
v1 = [1, 2, 3];
v2 = [4, 5, 6];

You can add these vectors element-wise as


follows:
sum_vector = v1+v2;
% Result: [5, 7, 9]

The dot product, which results in a single scalar


value, can be calculated using the dot function:

dot_product = dot(v1, v2); % Result: 32

42
Engineering with MATLAB: A Hands-on Introduction

For three-dimensional vectors, the cross-product


produces another vector:
cross_product = cross(v1, v2);
% Result: [-3, 6, -3]

Accessing and modifying specific elements of a


vector is straightforward using indices. MATLAB uses
1-based indexing, meaning the first element of a
vector has an index of 1. Here’s how

first_element = row_vector(1); %Result: 1


row_vector(3) = 10;
% Modified vector: [1, 2, 10, 4, 5]

MATLAB also allows you to create vectors with


regularly spaced elements using the colon operator :.
For example, to create a vector of numbers from 1 to
10 with a step size of 1:

regular_vector = 1:1:10;
% Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Or to create a vector from 0 to 2π with a step size


of π/4:
angle_vector = 0:pi/4:2*pi;
% Result: [0, 0.7854, 1.5708, 2.3562,
3.1416, 3.9270, 4.7124, 5.4978, 6.2832]

43
Engineering with MATLAB: A Hands-on Introduction

Another useful function for creating vectors is


linspace, which generates linearly spaced vectors. For
instance, to create a vector of 5 equally spaced points
between 0 and 1:
linear_space_vector = linspace(0, 1, 5);
% Result: [0, 0.25, 0.5, 0.75, 1]

Matrix Operations
Matrices in MATLAB are created similarly to
vectors but include multiple rows and columns. A
matrix can be created by separating rows with
semicolons within square brackets:

matrix_A = [1, 2, 3; 4, 5, 6; 7, 8, 9];

Matrices support a wide range of operations. For


example, you can add two matrices element-wise:

matrix_B = [9, 8, 7; 6, 5, 4; 3, 2, 1];


element_wise_sum = matrix_A + matrix_B;
% Result: [10,10,10;10,10,10;10,10,10]

Matrix multiplication, a crucial operation in


linear algebra, is performed using the asterisk
operator: matrix_C = [1, 2; 3, 4; 5, 6];
matrix_product = matrix_A * matrix_C;
% Result: [22, 28; 49, 64; 76, 100]
44
Engineering with MATLAB: A Hands-on Introduction

To transpose a matrix, which flips it over its


diagonal, use the apostrophe operator:

transpose_A = matrix_A';
% Result: [1, 4, 7; 2, 5, 8; 3, 6, 9]

The inverse of a matrix, if it exists, can be


calculated with the inv function:
inverse_A = inv(matrix_A);
% Note: matrix_A must be square and
invertible.

Calculating the determinant of a matrix is


another fundamental operation:

determinant_A = det(matrix_A);
% Result: 0 (for this specific matrix)

MATLAB also supports element-wise operations


for matrices using the dot operator. For example,
element-wise multiplication and division:

element_wise_product = matrix_A.*
matrix_B;
element_wise_division = matrix_A ./
matrix_B;

45
Engineering with MATLAB: A Hands-on Introduction

Special Matrices
MATLAB provides functions to create special
matrices that are often used in mathematical
computations. Some common special matrices
include:
• Identity Matrix: A square matrix with ones on
the main diagonal and zeros elsewhere.
identity_matrix = eye(3);
% Creates a 3x3 identity matrix.
• Zero Matrix: A matrix with all elements being
zero.
zero_matrix = zeros(3, 3);
% Creates a 3x3 matrix filled with zeros.
• Ones Matrix: A matrix with all elements being
one.
ones_matrix = ones(3, 3);
% Creates a 3x3 matrix filled with ones.
• Diagonal Matrix: A matrix with specified
elements on the main diagonal and zeros
elsewhere.
diagonal_matrix = diag([1, 2, 3]);
% Creates a diagonal matrix with elements
1, 2, and 3 on the diagonal.
• Magic Square: A magic square matrix where
the sum of elements in any row, column, or
diagonal is the same.
magic_square = magic(3);

46
Engineering with MATLAB: A Hands-on Introduction

• Hilbert Matrix: A matrix with elements being


the unit fractions.
hilbert_matrix = hilb(3);
% Creates a 3x3 Hilbert matrix.

• Pascal Matrix: A symmetric matrix with


binomial coefficients.
pascal_matrix = pascal(3);
% Creates a 3x3 Pascal matrix.

Linear Algebra in MATLAB


Linear algebra is the study of vectors, vector
spaces, and linear transformations. MATLAB
provides robust tools for performing linear algebra
operations. Some common operations include
solving systems of linear equations, eigenvalue and
eigenvector computation, and singular value
decomposition (SVD).
• Solving Systems of Linear Equations:
MATLAB can solve systems of linear equations
of the form 𝐴𝑥 = 𝐵 using the backslash operator
‘\’. For example, consider the system:

A = [1, 2; 3, 4];
b = [5; 6];
x = A \ b;
% Solution: x = [-4; 4.5]

47
Engineering with MATLAB: A Hands-on Introduction

• Eigenvalues and Eigenvectors: MATLAB


computes the eigenvalues and eigenvectors of
a matrix using the eig function. Eigenvalues
and eigenvectors are fundamental in
understanding the properties of matrices,
especially in stability analysis and vibrations.
[eigenvectors, eigenvalues] = eig(A);
% Returns matrices of eigenvectors and
eigenvalues.
• Singular Value Decomposition (SVD):
MATLAB performs SVD using the svd
function. SVD decomposes a matrix into three
other matrices and is used in signal processing,
statistics, and image compression.
[U, S, V] = svd(A);
% U, S, and V are the matrices from the
decomposition A = U*S*V'

Understanding and applying these operations is


crucial for many advanced applications, from solving
linear systems to performing data analysis and
dimensionality reduction.

Tables of Vector and Matrix Operations

48
Engineering with MATLAB: A Hands-on Introduction

Function
Category Description
Name
Creates a
vector with a
: (Colon
specified
Operator)
range and step
size.
Generates
linspace linearly spaced
Vector
vectors.
Operations
Computes the
dot dot product of
two vectors.
Computes the
cross product
cross
of two 3D
vectors.

Function
Category Description
Name
Adds two
Matrix
+ matrices
Operations
element-wise.
Multiplies two
*
matrices.
.* Element-wise

49
Engineering with MATLAB: A Hands-on Introduction

multiplication
of two
matrices.
Matrix Computes the
Operations inv inverse of a
matrix.
Computes the
det determinant
of a matrix.
Transposes a
transpose or '
matrix.

Function
Category Description
Name
Creates an
eye identity
matrix.
Special Creates a
Matrices zeros matrix filled
with zeros.
Creates a
ones matrix filled
with ones.
Creates a
diag diagonal
matrix from a

50
Engineering with MATLAB: A Hands-on Introduction

vector.

Creates a
magic magic square
Special matrix.
Matrices Creates a
hilb
Hilbert matrix.
pascal Creates a
Pascal matrix.

Function
Category Description
Name
Solves systems
\ of linear
equations.
Computes
Linear eigenvalues
Algebra eig
and
eigenvectors.

Performs
svd singular value
decomposition.

51
Engineering with MATLAB: A Hands-on Introduction

Function
Category Description
Name
size Returns the
size of a
matrix.
length Returns the
length of the
largest
dimension.
reshape Reshapes a
matrix to a
specified size.
Matrix Indexing numel Returns the
and number of
Manipulation elements in a
matrix.
find Finds indices
of non-zero
elements.
sub2ind Converts
subscripts to
linear indices.
ind2sub Converts linear
indices to
subscripts.

52
Engineering with MATLAB: A Hands-on Introduction

Function
Category Description
Name
sum Sums elements
of a matrix.
prod Computes the
product of
matrix
elements.
mean Computes the
mean of matrix
Matrix Element
elements.
Manipulation
median Computes the
median of
matrix
elements.
std Computes the
standard
deviation.

Vector Operations
Vectors are fundamental building blocks in
MATLAB. They can represent data sets, coefficients,
or any one-dimensional data structure. The colon
operator (:) is especially useful for creating vectors
with regularly spaced elements.
For example, 1:5 creates [1, 2, 3, 4, 5], and 0:0.5:2
53
Engineering with MATLAB: A Hands-on Introduction

creates [0, 0.5, 1, 1.5, 2]. The linspace function is used


for generating linearly spaced vectors when you need
a specific number of points. For example, linspace(1,
10, 4) generates [1, 4, 7, 10].
The dot and cross functions perform dot and
cross products, essential in vector calculus and
physics. For instance, the dot product of two vectors
[1, 2, 3] and [4, 5, 6] is 1*4 + 2*5 + 3*6 = 32.

Matrix Operations
Matrices are multi-dimensional arrays that
support a wide range of operations. Addition and
multiplication can be performed using + and *,
respectively. Element-wise operations use the dot
prefix, like .* for multiplication and ./ for division.
The inv function calculates the inverse of a matrix,
provided it is square and non-singular.
For example, inv([1, 2; 3, 4]) computes the inverse
of a 2x2 matrix. The det function calculates the
determinant, which is crucial in matrix theory and
applications involving volume scaling.

Special Matrices
Special matrices serve unique purposes in
mathematical modeling and simulation. The identity
matrix (eye) is used in linear transformations where it
acts as a neutral element. Zero matrices (zeros) and
54
Engineering with MATLAB: A Hands-on Introduction

ones matrices (ones) are useful for initializing arrays.


The diag function creates diagonal matrices, often
used in matrix diagonalization techniques. Magic
squares (magic), Hilbert matrices (hilb), and Pascal
matrices (pascal) have special properties used in
numerical analysis and combinatorial designs.

Linear Algebra
MATLAB excels in linear algebra operations. The
backslash operator (\) efficiently solves systems of
linear equations. Eigenvalues and eigenvectors,
computed using eig, are pivotal in stability analysis,
vibrations, and many other fields. Singular Value
Decomposition (SVD), performed using svd,
decomposes a matrix into singular vectors and
singular values, which is widely used in signal
processing, statistics, and image compression.

Matrix Indexing and Manipulation


Understanding matrix dimensions is crucial. The
size function returns the dimensions of a matrix, and
length returns the largest dimension. reshape
changes the dimensions of a matrix without altering
its data. find locates indices of non-zero elements,
and sub2ind and ind2sub convert between subscripts
and linear indices, facilitating advanced matrix
manipulations.
55
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 4

PROGRAMMING IN
MATLAB
In MATLAB, programming can be done using
scripts and functions. Both have distinct uses and
characteristics that make them suitable for different
types of tasks.
Scripts are files that contain a sequence of
MATLAB commands. They are used to automate
repetitive tasks, run a series of calculations, and batch
process data. Scripts do not accept input arguments
or return output arguments. All variables created in a
script exist in the base workspace, which can
sometimes lead to conflicts if variables are reused
unintentionally.
For example, consider a script to compute the
area of a circle:

% circle_area.m
radius = 5;
area = pi * radius^2;
disp(['The area is ', num2str(area)]);

In this script, the variable radius is assigned a

56
Engineering with MATLAB: A Hands-on Introduction

value, the area is calculated using the formula for the


area of a circle, and the result is displayed. The script
executes these commands sequentially when run.
Functions are more sophisticated and reusable
than scripts. They can accept input arguments and
return output arguments, making them suitable for
modular code. Functions have their own local
workspace, separate from the base workspace, which
helps avoid variable conflicts.
Function to calculate the area of a circle:

function area = circleArea(radius)


area = pi * radius^2;
end

To use this function, save it in a file named


circleArea.m, and call it from the command window
or another script:

radius = 5;
area = circleArea(radius);
disp(['The area of the circle is ',
num2str(area)]);

Functions can also have multiple input and


output arguments, allowing for more complex
operations and data handling.

57
Engineering with MATLAB: A Hands-on Introduction

Control Flow (if, for, while)


Control flow statements in MATLAB direct the
execution of code based on conditions and loops.
They are fundamental for creating complex and
dynamic programs.
1. If Statements allow conditional execution of
code. The structure is simple:

if condition
% Code to execute if condition is true
elseif another_condition
% Code to execute if another condition
is true
else
% Code to execute if none are true
End

Example:

x = 5;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end

58
Engineering with MATLAB: A Hands-on Introduction

In this example, the value of x is checked, and a


message is displayed based on whether x is positive,
negative, or zero.

2. For Loops are used for iterating over a range of


values. The basic syntax is:

for index = start_value:end_value


% Code to execute in each iteration
End

Example:

for i = 1:5
disp(['Iteration: ', num2str(i)]);
end

In this loop, the variable i takes values from 1 to 5,


and for each value, a message is displayed.

3. While Loops execute code as long as a


condition remains true. The syntax is:

while condition
% Code while the condition is true
End

59
Engineering with MATLAB: A Hands-on Introduction

Example:

i = 1;
while i <= 5
disp(['Iteration: ', num2str(i)]);
i = i + 1;
end

Here, the loop continues to execute as long as i is


less than or equal to 5. In each iteration, i is
incremented by 1.

Input and Output


Handling input and output in MATLAB is
essential for interactive programs and data
processing.
Input can be gathered using the input function.
This function prompts the user for input and returns
the entered value:

Input = input('Enter a value: ');


disp(['You entered: ', num2str(Input)]);

In this example, the user is prompted to enter a


value, which is then displayed.

60
Engineering with MATLAB: A Hands-on Introduction

Output can be displayed using disp, fprintf, or


other functions. The disp function is straightforward
for displaying messages:

disp('Hello, world!');

The fprintf function provides more flexibility


and supports formatting:

x = 10;
y = 20;
fprintf('x = %d, y = %d\n', x, y);

In this example, fprintf prints the values of x and


y with formatting.

For file input and output, MATLAB provides


several functions. Here’s how to write to a file:

fileID = fopen('output.txt', 'w');


fprintf(fileID, 'Hello, world!\n');
fclose(fileID);

This code opens a file for writing, writes a string


to the file, and then closes the file. This function is
particularly helpful to log calculated results in a
proper manner

61
Engineering with MATLAB: A Hands-on Introduction

To read from a file:

fileID = fopen('output.txt', 'r');


data = fscanf(fileID, '%s');
fclose(fileID);
disp(['File contains: ', data]);

This code opens a file for reading, reads the


contents, and displays them.

Error Handling
Error handling ensures your code can manage
unexpected situations elegantly. This method is
particularly helpful in managing large pieces of code
to find for errors. The try-catch construct is used for
this purpose.
The basic syntax of try-catch is:

try
% Code that might produce an error
catch exception
% Code to execute if an error occurs
disp('An error occurred:');
disp(exception.message);
end

62
Engineering with MATLAB: A Hands-on Introduction

Example:

try
result = 10 / 0; % Invalid Calculation
catch exception
disp('An error occurred:');
disp(exception.message);
end

In this example, an attempt to divide by zero


triggers an error, which is then caught and handled
by displaying an error message.

Best Practices in MATLAB Programming


Adopting best practices in MATLAB
programming is crucial for developing code that is
efficient, maintainable, and easy to understand.
These practices will ensure the code maintains a
steady workflow and and ensures reliability.

Code Organization
1. Modular Code: Divide your code into discrete,
manageable sections by using functions and scripts.
Each function or script should perform a specific task.
For example, instead of creating one long script that
reads data, processes it, and displays results, you
should break it down into separate functions for each
63
Engineering with MATLAB: A Hands-on Introduction

of these tasks. This modular approach enhances code


readability and reuse.

% Example of modular code


% Main script
data = readData('data.csv');
processedData = processData(data);
displayResults(processedData);

% Function definitions
function data = readData(filename)
data = readtable(filename);
end

function processedData = processData(data)


% Data processing steps
end

function displayResults(data)
% Code to display results
End

2. File and Folder Structure: Organize your files


into a coherent folder structure. This helps you and
others to navigate through the project easily.
3. Naming Conventions: Use clear and
descriptive names for files and functions. Avoid
vague names like test.m or data1.m. Instead, use
64
Engineering with MATLAB: A Hands-on Introduction

names that describe the content or purpose, such as


importData.m or calculateStatistics.m.

Commenting and Documentation


Proper documentation is crucial for
understanding, maintaining, and sharing your code.
MATLAB provides several ways to document your
work effectively.
1. Inline Comments: Use inline comments to
explain specific lines or sections of your code,
especially if they perform complex or non-
obvious operations. Keep comments concise
and focused.

% Calculate the area of a circle


radius = 5; % Radius of the circle
area = pi * radius^2; % Area formula

2. Function Headers: Provide a header comment


for each function, detailing its purpose, inputs,
outputs, and any relevant details. This makes it
easier for others to understand what the
function does without reading the entire code.

% CIRCLEAREA Calculate the area of a


circle
% AREA = CIRCLEAREA(RADIUS) returns
65
Engineering with MATLAB: A Hands-on Introduction

the area of a circle with the specified


radius.
%
% Input:
% RADIUS - The radius of the
circle (numeric)
%
% Output:
% AREA - The calculated area of
the circle (numeric)

function area = circleArea(radius)


area = pi * radius^2;
end

3. Help Text for Scripts: Include a comment


block at the beginning of your scripts to
explain what the script does and how to use it.
This information can be accessed using the
help command. This method is generally used
for very large scripts where individual
commenting isn’t possible.
4. Variable Naming: Using meaningful and
consistent variable names is essential for
making your code readable and maintainable.
• Descriptive Names: Choose names that
clearly describe the variable's purpose or
content. Avoid single-letter names or

66
Engineering with MATLAB: A Hands-on Introduction

abbreviations that aren't immediately


obvious.

• Consistent Naming Conventions: Stick


to a consistent naming convention
throughout your code. Common
conventions include camelCase (e.g.,
circleArea) and snake_case (e.g.,
circle_area).
• Avoid Reserved Words: Do not use
MATLAB reserved words or names of
built-in functions for your variables, as
this can lead to confusion and errors.
mean = 10;

% This can cause problems because


'mean' is a built-in function

Performance Optimization
Optimizing your code can significantly improve
its execution speed and efficiency. MATLAB provides
several tools and techniques to help identify and
optimize performance bottlenecks.
1. Profiling Code: Use the MATLAB Profiler to
identify which parts of your code are taking the
most time. The profiler provides detailed
information about function calls and execution
times.

67
Engineering with MATLAB: A Hands-on Introduction

profile on
% Your code here
profile off
profile viewer
2. Optimizing Loops: Whenever possible,
convert loops to vectorized operations. Also,
preallocate memory for arrays and avoid
growing arrays dynamically inside loops.
3. Efficient Use of Functions: Inline small
functions or use built-in functions that are
optimized for performance. MATLAB’s built-
in functions are often more efficient than
custom implementations.

% Example of using built-in function for


matrix multiplication
A = rand(1000);
B = rand(1000);
C = A * B; % More efficient than
implementing matrix multiplication manually

4. Memory Management: Manage memory


efficiently by clearing large variables that are
no longer needed. Use the clear function to
free up memory and avoid using global
variables.

% Clear large variables


68
Engineering with MATLAB: A Hands-on Introduction

clear largeVariable;

Mastering the best practices in MATLAB


programming is essential for developing robust,
efficient, and maintainable code. You can
significantly enhance your programming skills by
organizing your code effectively, using meaningful
variable names, leveraging vectorized operations,
and implementing comprehensive error handling.
Optimizing performance and maintaining code
readability through consistent formatting and
thorough documentation will ensure your MATLAB
projects are professional and sustainable. As you
continue to apply these practices, you'll find that your
coding becomes more powerful, enjoyable, and
collaborative.

Chapter Revision In Tabular Form

69
Engineering with MATLAB: A Hands-on Introduction

Category Function Name Description


Defines a
reusable
block of
function
code with
inputs and
outputs.
Terminates
end
a function.
Example
[output1, output2] = function call
function_name(input1, with
input2) multiple
Functions outputs.
Returns the
number of
input
nargin
arguments
passed to a
function.
Returns the
number of
nargout
output
arguments.

70
Engineering with MATLAB: A Hands-on Introduction

Control Flow

Category Command/Syntax Description


Executes
If if condition, statements if
Statement statements, end the condition is
true.
Executes if the
preceding if
condition is
elseif condition,
Elseif false and the
statements
current
condition is
true.
Repeats
for index = values, statements for
For Loop
statements, end each value in
the index.
Repeats
statements
While while condition,
while the
Loop statements, end
condition is
true.

71
Engineering with MATLAB: A Hands-on Introduction

Input and Output

Category Command/Syntax Description


Prompts the
user for input
Input input(prompt)
and returns the
value.
Displays a
Output disp(message) message or
value.
Loads data from
File Input load(filename) a .mat file into
the workspace.
Saves variables
File save(filename,
from the
Output variables)
workspace
try, statements, Executes
Try-Catch
catch exception, statements and
Block
statements, end catches errors.
Throws an error
Error
error('message') and displays a
Function
message.
Displays a
Warning
warning('message') warning
Function
message..

72
Engineering with MATLAB: A Hands-on Introduction

Best Practices in MATLAB Programming

Command/
Category Description
Syntax
Divide code into
functions and
Code Modular
scripts for
Structure Code
reusability and
readability.
Use clear and
descriptive
Naming Descriptive names for
Conventions Names variables,
functions, and
scripts.
Use comments to
Inline explain specific
Comments
Comments lines or sections
of code.
Provide header
comments for
Function each function
Function
Documentatio describing its
Headers
n purpose, inputs,
and outputs

73
Engineering with MATLAB: A Hands-on Introduction

Follow consistent
Code Consistent formatting rules
Formatting Formatting for indentation
and spacing.
Use array
operations
Vectorized
Vectorization instead of loops
Operations
for better
performance.
Use version
Version control systems
Version
Control like Git for
Control
Systems collaboration and
tracking changes.

These tables and detailed descriptions provide a


comprehensive overview of key programming
concepts and commands in MATLAB. Each entry is
accompanied by examples and explanations to
illustrate their usage, helping you to understand how
to implement these practices in your own work.
Mastering these elements will significantly enhance
your proficiency in MATLAB, enabling you to write
more efficient, readable, and maintainable code.

74
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 5

DATA
VISUALIZATION IN
MATLAB
Data visualization is a powerful means of
understanding and communicating data. It involves
the creation of graphical representations of data to
identify patterns, trends, and relationships that might
not be apparent from raw numbers alone. MATLAB,
a high-level language and interactive environment, is
particularly well-suited for data visualization,
offering a wide array of functions to create
everything from simple plots to complex, interactive
graphics.

Basics of Plots
Plots are visual representations of data points.
They help in comprehending large amounts of data
and complex relationships. Plots can be categorized
broadly into 2D plots, 3D plots, and specialized
graphics. Plots are essential tools in data analysis and
visualization because they enable pattern
recognition, allowing us to easily identify trends,

75
Engineering with MATLAB: A Hands-on Introduction

cycles, and outliers within datasets. By visualizing


data, we can compare different datasets or variables
more effectively, enhancing our ability to discern
relationships and differences. Furthermore, plots
help in summarizing large volumes of data into more
understandable visuals, making complex information
more accessible. This is particularly useful for
communication, as well-designed plots can
effectively present data findings in a visually
appealing manner, making them easier to interpret
and share with others.
Using plots in MATLAB involves several key
steps. First, is data preparation; this step involves
organizing and preprocessing your data to ensure it is
in the correct format and ready for analysis. Once the
data is prepared, plot creation follows, utilizing
MATLAB's robust functions to generate the necessary
visual representations. After creating the initial plot,
customization comes into play. This involves
adjusting the plot's appearance to improve clarity and
aesthetics, such as adding labels, titles, and legends,
and modifying colors or line styles. Finally, the
analysis phase involves interpreting the plots to draw
meaningful conclusions from the data. By examining
the visualized data, we can gain insights and make
informed decisions based on the patterns and trends
observed.
76
Engineering with MATLAB: A Hands-on Introduction

Plotting Basics
In MATLAB, plotting starts with the plot()
function, which is used to create 2D line plots. This
function can handle simple to moderately complex
plots with ease.

x = linspace(0, 2*pi, 100);


% Generate 100 points between 0 and 2*pi
y = sin(x);
% Compute the sine of each point
plot(x, y); % Create a 2D line plot
xlabel('X-axis'); % Label the x-axis
ylabel('Y-axis'); % Label the y-axis
title('Sine Wave');
% Add a title to the plot
grid on; % Display grid lines

In this example:
• linspace(0, 2*pi, 100) creates a vector x with
100 points between 0 and 2π2\pi2π.
• sin(x) computes the sine of each point in x.
• plot(x, y) generates a plot of y against x.
• xlabel, ylabel, and title add labels and a title to
the plot.
• grid on turns on the grid for better readability.

77
Engineering with MATLAB: A Hands-on Introduction

These basic functions can be used to plot any


graph with any desired value.

Output:

2D and 3D Plots
In MATLAB, creating 2D and 3D plots is important
for visualizing data in various dimensions,
making it easier to understand and analyze
complex datasets.
2D Plots
2D plots are the most common type of plots used
to display data with two variables, typically in the
form of x and y coordinates. They are used to
represent relationships between variables, trends
over time, and distributions.
78
Engineering with MATLAB: A Hands-on Introduction

Creating a Basic 2D Plot: The plot function is the


primary tool for creating 2D plots.

x = 0:0.1:10;
y = sin(x);
plot(x, y);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');

Output:

79
Engineering with MATLAB: A Hands-on Introduction

Scatter Plots: For displaying individual data


points, scatter plots are useful.

x = rand(1, 100);
y = rand(1, 100);
scatter(x, y);
title('Scatter Plot');
xlabel('x');
ylabel('y');

Output:

80
Engineering with MATLAB: A Hands-on Introduction

Bar Graphs: To compare quantities, bar graphs


are effective.
categories = {'A', 'B', 'C'};
values = [23, 45, 10];
bar(categories, values);
title('Bar Graph');
xlabel('Category');
ylabel('Value');
Output:

81
Engineering with MATLAB: A Hands-on Introduction

3D Plots
Creating and working with 3D plots in MATLAB
allows you to visualize data in three dimensions,
adding depth to your data analysis and presentation.

Basics of 3D Plots
3D plots involve three coordinates: x, y, and z.
These plots are particularly useful for visualizing data
that changes over two independent variables,
providing a more comprehensive understanding of
the data structure and patterns.

Types of 3D Plots

1. 3D Line Plots: 3D line plots are used to display


trajectories or paths in three-dimensional
space.

t = 0:0.1:10;
x = sin(t);
y = cos(t);
z = t;
plot3(x, y, z, 'LineWidth', 2);
title('3D Line Plot');
xlabel('x');
ylabel('y');
zlabel('z');
82
Engineering with MATLAB: A Hands-on Introduction

grid on;

Output:

2. Surface Plots: Surface plots display a surface


defined by a function of two variables,
z = f(x, y).

[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);


Z = X.^2 - Y.^2;
surf(X, Y, Z);
title('Surface Plot');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
colormap jet;
83
Engineering with MATLAB: A Hands-on Introduction

colorbar;
Output:

3. Mesh Plots: Mesh plots create a wireframe


representation of the surface.

[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);


Z = sin(X) + cos(Y);
mesh(X, Y, Z);
title('Mesh Plot');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');

84
Engineering with MATLAB: A Hands-on Introduction

Output:

4. Contour Plots: Contour plots are used to show


level curves of a surface function on the x-y
plane.

[X, Y]=meshgrid(-5:0.5:5, -5:0.5:5);


Z = sin(sqrt(X.^2 + Y.^2));
contour3(X, Y, Z, 20);
title('3D Contour Plot');
xlabel('X-axis');
ylabel('Y-axis');
85
Engineering with MATLAB: A Hands-on Introduction

zlabel('Z-axis');

Output:

5. Scatter Plots in 3D: Scatter plots can also be


extended to three dimensions.

x = randn(100, 1);
y = randn(100, 1);
z = randn(100, 1);
scatter3(x, y, z, 'filled');
title('3D Scatter Plot');
xlabel('x');
ylabel('y');
zlabel('z');
86
Engineering with MATLAB: A Hands-on Introduction

grid on;

Output:

Customizing 3D Plots
Customization enhances the readability and
aesthetic appeal of 3D plots. MATLAB provides
numerous options to fine-tune the appearance of
your plots.
• View Angle: Control the view angle using
view function.

view(45, 30);

87
Engineering with MATLAB: A Hands-on Introduction

• Lighting and Shading: Add lighting and


shading effects to improve visual
perception.

surf(X, Y, Z);
shading interp;
camlight;
lighting phong;

• Color Mapping: Use colormap to change


the color scheme of the plot.

colormap hot;
colorbar;

• Adding Annotations: Annotations such as


titles, labels, and legends make the plot
more informative.

title('Annotated 3D Plot');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
legend({'Data'}, 'Location',
'northeast');

88
Engineering with MATLAB: A Hands-on Introduction

• Line and Marker Customization: You can


change the style, color, and markers of
lines in your plot.

plot(x, y, '-.r', 'LineWidth', 3,


'Marker', 'o');
% Red dash-dot line with circular
markers

1. '-' specifies a solid line, '--' a dashed line, ':' a


dotted line, and '-. ' a dash-dot line.
2. 'r' sets the color to red. Other colors include 'b'
(blue), 'g' (green), 'k' (black), etc.
3. 'LineWidth' sets the width of the line.
'Marker' specifies the marker type, such as 'o' for
circles and '+' for plus signs.

Working with Images and Graphics


MATLAB provides robust tools for working
with images and graphics, making it a powerful
platform for image & graphic processing.

Image Handling
MATLAB provides tools for working with
images and graphics, making it a powerful platform
for image processing and graphical manipulations.

89
Engineering with MATLAB: A Hands-on Introduction

1. Reading and Displaying Images: Use imread


to read an image file and imshow to display it.

img = imread('example.jpg');
imshow(img);
title('Original Image');

2. Image Formats: MATLAB supports various


image formats including JPEG, PNG, TIFF, and
BMP. The format of an image determines how
it is stored and processed.

img_png = imread('example.png');
img_tiff = imread('example.tiff');

3. Converting Image Types: Convert between


different image types (e.g., RGB to grayscale).

gray_img = rgb2gray(img);
imshow(gray_img);
title('Grayscale Image');

4. Image Resizing: Resize images to your desired


size using imresize.

resized_img = imresize(img, 0.5);


90
Engineering with MATLAB: A Hands-on Introduction

imshow(resized_img);
title('Resized Image');

5. Image Transformation: Transform images


using geometric transformations such as
rotation and translation.

• Rotation:

rotated_img = imrotate(img, 45);


imshow(rotated_img);
title('Rotated Image');

Graphics in MATLAB
MATLAB also offers extensive capabilities for
creating and manipulating graphical objects, which
are essential for developing custom visualizations
and user interfaces.

• Basic Shapes: Use functions like rectangle,


ellipse, and line to create shapes.

figure;
rectangle('Position', [0.1, 0.1, 0.3,
0.3], 'FaceColor', 'r');
hold on;

91
Engineering with MATLAB: A Hands-on Introduction

rectangle('Position', [0.5, 0.5, 0.3,


0.3], 'Curvature', [1, 1],
'FaceColor', 'b');
plot([0, 1], [0, 1], 'k--');
title('Basic Shapes');
hold off;

Output:

• Annotating Plots: Add annotations such as


text, arrows, and legends to enhance the
readability of plots.

92
Engineering with MATLAB: A Hands-on Introduction

x = 0:0.1:10;
y = sin(x);
plot(x, y);
text(5, 0, 'Peak',
'HorizontalAlignment', 'center');
annotation('arrow', [0.5, 0.7], [0.5,
0.8]);
legend('Sine Wave');
title('Annotated Plot');

Output:

93
Engineering with MATLAB: A Hands-on Introduction

• Interactive Graphics: Create interactive


graphics using functions like ginput and
uicontrol.

figure;
plot(x, y);
title('Click on the plot');
[x_click, y_click] = ginput(1);
hold on;
plot(x_click, y_click, 'ro');
hold off;

Output:

94
Engineering with MATLAB: A Hands-on Introduction

• 3D Graphics: Manipulate and display 3D


graphical objects.

[X, Y, Z] = peaks;
figure;
surf(X, Y, Z);
shading interp;
light;
camlight left;
title('3D Surface with Lighting');

Output:

95
Engineering with MATLAB: A Hands-on Introduction

• Animations: Create animations by


updating plots in a loop.

figure;
h = plot(x, y);
for k = 1:length(x)
set(h, 'YData', sin(x + 0.1*k));
drawnow;
pause(0.1);
end

Output:

96
Engineering with MATLAB: A Hands-on Introduction

Mastering data visualization in MATLAB is crucial for


effectively analyzing and presenting your data. From
basic plotting functions to advanced image
processing and 3D graphics, MATLAB offers a
comprehensive suite of tools to help you convey your
findings clearly and effectively. Whether you're
identifying patterns in large datasets, creating custom
plots, or developing interactive graphics, the skills
covered in this chapter will empower you to utilize
MATLAB's visualization capabilities to their fullest
potential. With practice, you'll be able to create
compelling visual representations that not only
enhance your data analysis but also improve your
ability to communicate complex information in a
visually intuitive manner.

97
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 6

WORKING WITH
DATA
Data visualization is a powerful means of
understanding and communicating data. It involves
the creation of graphical representations of data to
identify patterns, trends, and relationships that might
not be apparent from raw numbers alone. MATLAB,
a high-level language and interactive environment, is
particularly well-suited for data visualization,
offering a wide array of functions to create
everything from simple plots to complex, interactive
graphics.

Importing Data
MATLAB supports a variety of data formats, each
with specific functions tailored to facilitate easy and
efficient data importation. Here are the most
commonly used methods:

• Reading CSV Files


CSV (Comma-Separated Values) files are widely
used for storing tabular data due to their simplicity
and compatibility with numerous applications. In
98
Engineering with MATLAB: A Hands-on Introduction

MATLAB, the readtable function is commonly used


to read CSV files, converting them into table data
structures that support heterogeneous data types and
offer extensive data manipulation capabilities.

data = readtable('data.csv');
disp(data);

Loading a Demo Dataset, we get the following


output:

• Reading EXCEL Files

data = readtable('data.xlsx');
disp(data);

• Reading MAT-Files
MAT-files are MATLAB's native format for
storing variables. They provide efficient storage and
quick access for large datasets, preserving variable
99
Engineering with MATLAB: A Hands-on Introduction

types and structures. The load function is used to


import data from MAT-files.

load('data.mat');
disp(data);

Exporting Data
Once your data analysis is complete, exporting
the results is often necessary for reporting or further
use in other applications. MATLAB provides several
functions for exporting data to various formats:

• Writing to CSV, EXCEL and MAT Files


To export data to a CSV file, use the writetable
function. This function is useful for ensuring
compatibility with other data analysis tools
supporting CSV format.

writetable(data, 'output.csv');

Similarly, MATLAB can export data to Excel files


using the writetable or xlswrite functions, providing a
seamless way to share data with users who prefer
Excel.
To save your MATLAB variables for later use, the
save function writes data to MAT-files, preserving all
variable types and structures efficiently.
100
Engineering with MATLAB: A Hands-on Introduction

save('data.mat', 'data');

By understanding and utilizing these functions


for importing and exporting data, you can streamline
your data workflow in MATLAB, ensuring that you
can easily bring in external data for analysis and
export your results for sharing or further use.

Data Preprocessing and Cleaning


Data preprocessing and cleaning are essential
steps in data analysis. In real-world scenarios, data is
often incomplete, noisy, or inconsistent, which can
significantly impact the quality of the results.
MATLAB provides various tools and functions to
preprocess and clean data effectively, ensuring that
the subsequent analysis is accurate and meaningful.

Understanding Data Preprocessing and Cleaning


Data preprocessing involves transforming raw
data into a format suitable for analysis. This includes
handling missing values, normalizing data, and
identifying outliers. Data cleaning, on the other hand,
focuses on correcting errors and inconsistencies
within the dataset.

101
Engineering with MATLAB: A Hands-on Introduction

• Handling Missing Values


Missing data can lead to biased results and
erroneous conclusions. MATLAB offers several
methods to handle missing values, including
imputation and deletion. The fillmissing function is
commonly used for this purpose.

data = [1, NaN, 3; 4, 5, NaN; 7, 8, 9];


cleanedData = fillmissing(data, 'linear');
disp(cleanedData);

Output:

• Normalizing Data
Normalization is the process of scaling data to a
standard range. This is particularly useful when
dealing with features that have different units or
scales. MATLAB provides the normalized function
for this purpose.

data = rand(5, 3) * 100;


normalizedData = normalize(data, 'range');
disp(normalizedData);

102
Engineering with MATLAB: A Hands-on Introduction

Output:

• Identifying and Handling Outliers


Outliers can distort statistical analyses and
models. MATLAB's isoutlier function helps detect
outliers, and the filloutliers function can handle
them.

data = [1, 2, 3, 100, 5, 6, 7];


outlierIndices = isoutlier(data);
cleanedData = filloutliers(data,
'linear');
disp(outlierIndices);
disp(cleanedData);

Output:

103
Engineering with MATLAB: A Hands-on Introduction

Basic Statistics in MATLAB

Understanding the statistical properties of data is


a fundamental aspect of data analysis. MATLAB
provides a wide range of functions to compute
descriptive statistics, perform hypothesis testing, and
more.
• Descriptive Statistics
Descriptive statistics summarize the main
features of a dataset. Common descriptive statistics
include the mean, median, standard deviation, and
variance.

data = randn(100, 1);


meanValue = mean(data);
medianValue = median(data);
stdValue = std(data);
varValue = var(data);
disp(['Mean: ', num2str(meanValue)]);
disp(['Median: ', num2str(medianValue)]);
disp(['Standard Deviation: ',
num2str(stdValue)]);
disp(['Variance: ', num2str(varValue)]);

Output:

104
Engineering with MATLAB: A Hands-on Introduction

• Hypothesis Testing
Hypothesis testing is used to make inferences
about populations based on sample data. MATLAB
provides functions for various statistical tests,
including t-tests, chi-square tests, and ANOVA.

data1 = randn(100, 1);


data2 = randn(100, 1) + 0.5;
% Shift the mean
[h, p] = ttest2(data1, data2);
disp([' Test Result: ', num2str(h)]);
disp(['P-value: ', num2str(p)]);

Output:

• Correlation and Covariance


Correlation and covariance measure the
relationship between two variables. MATLAB's
corrcoef and cov functions are used to compute these
metrics.

data1 = randn(100, 1);


data2 = data1 + randn(100, 1) * 0.5;
CorrMatrix = corrcoef(data1, data2);
covarianceMatrix = cov(data1, data2);
105
Engineering with MATLAB: A Hands-on Introduction

disp('Correlation Matrix:');
disp(CorrMatrix);
disp('Covariance Matrix:');
disp(covarianceMatrix);

Output:

Data Analysis Techniques

Data analysis techniques encompass a wide range


of methods that help in extracting meaningful
insights from data. MATLAB, with its extensive
library of functions and tools, offers powerful
capabilities for performing various data analysis
tasks. In this section, we will learn some of the most
commonly used data analysis techniques, including
clustering, regression analysis, and time-series
analysis. Each technique will be explained in detail,
along with examples to illustrate their application in
MATLAB.

106
Engineering with MATLAB: A Hands-on Introduction

1. Clustering
Clustering is a technique used to group similar
data points together based on certain characteristics.
It is an unsupervised learning method, meaning it
does not require labeled data. Clustering can help in
identifying patterns and structures in data, which are
not immediately apparent.
a) K-means Clustering: This is one of the most
popular clustering methods. It partitions data
into K distinct clusters based on their features.
The algorithm iteratively assigns each data
point to the nearest cluster center and then
recalculates the cluster centers until
convergence.
b) Hierarchical Clustering: This method builds a
hierarchy of clusters either in a bottom-up or
top-down approach. It can be represented as a
dendrogram, which visualizes the tree
structure of the clusters.
c) DBSCAN (Density-Based Spatial Clustering
of Applications with Noise): This algorithm
groups together points that are closely packed
together and marks points that are in low-
density regions as outliers.

107
Engineering with MATLAB: A Hands-on Introduction

• K-means Clustering in MATLAB


The kmeans function in MATLAB is used to
perform K-means clustering.
% Generate sample data
data = [randn(50, 2); randn(50, 2) + 5];
% Perform K-means clustering with 2
clusters
[idx, C] = kmeans(data, 2);
% Plot the clustered data
figure;
scatter(data(:,1), data(:,2), 10, idx,
'filled');
hold on;
plot(C(:,1), C(:,2), 'kx', 'MarkerSize',
15, 'LineWidth', 3);
title('K-means Clustering');
xlabel('Feature 1');
ylabel('Feature 2');
legend('Cluster 1', 'Cluster 2',
'Centroids');
hold off;

In this example, we generate a two-


dimensional dataset with two clusters. The
kmeans function partitions the data into two
clusters, and the results are visualized using a
scatter plot with different colors for each
cluster and marked centroids.

108
Engineering with MATLAB: A Hands-on Introduction

Output:

• Hierarchical Clustering in MATLAB


Hierarchical clustering can be performed using
the linkage and cluster functions. The dendrogram
function helps visualize the hierarchical structure.

% Generate sample data


data = [randn(50, 2); randn(50, 2) + 5];
% Perform hierarchical clustering
Z = linkage(data, 'ward');
T = cluster(Z, 'maxclust', 2);
% Plot the dendrogram
figure;
dendrogram(Z);
title('Hierarchical Clustering );
109
Engineering with MATLAB: A Hands-on Introduction

xlabel('Sample Index');
ylabel('Distance');
% Plot the clustered data
figure;
scatter(data(:,1), data(:,2), 10, T,
'filled');
title('Hierarchical Clustering');
xlabel('Feature 1');
ylabel('Feature 2');
legend('Cluster 1', 'Cluster 2');

Output:

110
Engineering with MATLAB: A Hands-on Introduction

In this example, we use the Ward method for


hierarchical clustering and visualize the results
using a dendrogram and a scatter plot.
Regression Analysis
Regression analysis is a statistical technique used
to model the relationship between a dependent
variable and one or more independent variables. It
helps in predicting the dependent variable based on
the values of the independent variables.
Types of Regression
1. Linear Regression: This models the
relationship between two variables by fitting a
linear equation to the observed data. It assumes
a straight-line relationship between the
dependent and independent variables.
2. Multiple Linear Regression: This extends
linear regression to include multiple
independent variables.
3. Polynomial Regression: This models the
relationship between the dependent variable
and the independent variables as an nth degree
polynomial.
4. Logistic Regression: This is used for binary
classification problems and models the
probability of the dependent variable
belonging to a particular category.

111
Engineering with MATLAB: A Hands-on Introduction

• Linear Regression in MATLAB


The fitlm function in MATLAB is used for linear
regression. Here is a detailed example:

% Generate sample data


x = (1:10)';
y = 2*x + randn(10, 1);
% Fit a linear model
model = fitlm(x, y);
% Display the model
disp(model);
% Plot the regression line
figure;
plot(model);
title('Linear Regression');
xlabel('X');
ylabel('Y');
legend('Data', 'Fit', 'Confidence
Bounds');
Output

112
Engineering with MATLAB: A Hands-on Introduction

In this example, we generate a simple linear


relationship between x and y with some noise.
The fitlm function fits a linear model to the
data, and the regression line is plotted.

• Multiple Linear Regression in MATLAB


Multiple linear regression can be performed
using the fitlm function as well.

% Generate sample data


X = [ones(10,1) (1:10)' (1:10)'.^2];
y = 2*X(:,2) + 3*X(:,3) + randn(10,1);
% Fit a multiple linear model
model = fitlm(X, y);

% Display the model


disp(model);

In this example, we fit a multiple linear


regression model to data with two independent
variables, X(:,2) and X(:,3), and one dependent
variable y.

113
Engineering with MATLAB: A Hands-on Introduction

Output:

• Time-Series Analysis
Time-series analysis involves analyzing data
points collected or recorded at specific time intervals.
It is used in various fields such as finance, economics,
environmental science, and more. MATLAB provides
powerful tools for time-series analysis, including
functions for frequency analysis, autocorrelation, and
filtering.
Key Concepts in Time-Series Analysis
1. Trend: The long-term movement or direction
in the data.
2. Seasonality: Regular patterns or cycles in the
data occurring at specific intervals.
3. Noise: Random variation in the data that
cannot be explained by the model.

114
Engineering with MATLAB: A Hands-on Introduction

Frequency Analysis
Frequency analysis involves decomposing a time-
series signal into its constituent frequencies. The fft
function in MATLAB is used for this purpose.

• Fourier Transform
% Generate sample data
t = 0:0.01:10;
data = sin(2*pi*1*t) + sin(2*pi*2*t) +
0.5*randn(size(t));

% Perform Fourier Transform


fftData = fft(data);

% Plot the time-series data


figure;
subplot(2,1,1);
plot(t, data);
title('Time-Series Data');
xlabel('Time');
ylabel('Amplitude');

% Plot the frequency-domain data


f = (0:length(fftData)-1)*(1/(2*max(t)));
subplot(2,1,2);
plot(f, abs(fftData));
title('Frequency Domain');
xlabel('Frequency');
ylabel('Magnitude');
115
Engineering with MATLAB: A Hands-on Introduction

Output:

In this example, we generate a time-series


signal composed of two sine waves with added
noise. The fft function is used to transform the
signal into the frequency domain.

• Autocorrelation
Autocorrelation measures the correlation of a
signal with a delayed copy of itself. The
autocorr function in MATLAB is used to
compute and plot the autocorrelation function.

116
Engineering with MATLAB: A Hands-on Introduction

% Generate sample data


data = sin(2*pi*(0:0.01:10)) +
0.5*randn(1, 1001);
% Compute and plot autocorrelation
figure;
autocorr(data);
title('Autocorrelation of Time-Series
Data');

Output:

117
Engineering with MATLAB: A Hands-on Introduction

• Filtering
Filtering is used to remove noise from a signal
or to extract specific frequency components.
MATLAB provides various functions for
filtering, including filter, butter, and fir1.

% Generate sample data


t = 0:0.01:10;
data = sin(2*pi*1*t) + sin(2*pi*10*t) +
0.5*randn(size(t));
% Design a low-pass filter
[b, a] = butter(4, 0.1, 'low');
% Apply the filter
filteredData = filter(b, a, data);
% Plot the original and filtered data
figure;
subplot(2,1,1);
plot(t, data);
title('Original Data');
xlabel('Time');
ylabel('Amplitude');
subplot(2,1,2);
plot(t, filteredData);
title('Filtered Data');
xlabel('Time');
ylabel('Amplitude');

118
Engineering with MATLAB: A Hands-on Introduction

Output:

These methods are powerful tools for extracting


meaningful insights from data, and mastering them
will enhance your ability to analyze and interpret
complex datasets. By understanding and applying
these techniques, you can effectively transform raw
data into valuable information, supporting informed
decision-making and advancing your analytical
capabilities.

119
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 7

TOOLBOXES AND
APPLICATIONS
MATLAB is a high-performance language for
technical computing that integrates computation,
visualization, and programming. One of its most
powerful features is its extensive suite of toolboxes.
Toolboxes in MATLAB are comprehensive
collections of functions that extend their capabilities
to solve particular classes of problems. They cover a
broad range of applications including signal
processing, image processing, control systems,
machine learning, statistics, optimization, and much
more. Each toolbox is designed to provide
sophisticated algorithms and functions tailored for
specific domains, making MATLAB a versatile tool
for engineers, scientists, and researchers.

How to Install MATLAB Toolboxes


Famous and commonly used MATLAB toolboxes
are usually installed while installing MATLAB itself,
while the users can opt out of installing extra addons
to save space we can install addons on through the
following way:
120
Engineering with MATLAB: A Hands-on Introduction

1. Open MATLAB: Start by launching MATLAB


on your computer. Ensure that you have an
active internet connection, as the installation
process requires downloading files from
MathWorks.
2. Access the Add-On Explorer: Click on the
“Add-Ons” icon located on the MATLAB
toolbar. This icon usually resembles a package
or a shopping cart.

3. Open the Add-On Explorer: Clicking the Add-


Ons icon will open the Add-On Explorer
window, where you can browse all available
toolboxes, apps, and hardware support
packages.
4. Search for the Toolbox: In the Add-On
Explorer, use the search bar to type in the
name of the toolbox you want to install. For
121
Engineering with MATLAB: A Hands-on Introduction

example, if you are looking for the Signal


Processing Toolbox, type “Signal Processing
Toolbox” into the search bar and press Enter.
5. Select the Toolbox: From the search results,
click on the toolbox you wish to install. This
action will open a detailed page about the
toolbox, including a description, features, and
system requirements.

6. Click Install: On the toolbox's detailed page,


click the “Install” button. MATLAB will then
prompt you to log in to your MathWorks
account if you are not already logged in. Enter
your credentials to proceed.
7. Follow Installation Prompts: MATLAB will
handle the download and installation process.
Follow any additional prompts or instructions
provided. The progress of the installation will

122
Engineering with MATLAB: A Hands-on Introduction

be displayed, and once completed, MATLAB


will notify you.
8. Verify Installation: To verify that the toolbox
has been successfully installed, you can use the
ver command in the Command Window. This
command will list all installed products along
with their version numbers.

In this book we will be covering basics of mainly


three ToolBoxes
In this book, we will be covering the basics of four
essential MATLAB toolboxes that are fundamental
for a wide range of applications:
1. Signal Processing Toolbox: This toolbox
provides a comprehensive set of functions for
analyzing and manipulating signals. Whether
you are working with audio, communications,
or biomedical signals, the Signal Processing
Toolbox offers tools for filter design, spectral
analysis, and time-frequency analysis, enabling
123
Engineering with MATLAB: A Hands-on Introduction

you to process and understand signal data


effectively.
2. Image Processing Toolbox: With the Image
Processing Toolbox, you can perform a variety
of image processing tasks, such as image
enhancement, segmentation, and feature
extraction. This toolbox is crucial for
applications in medical imaging, remote
sensing, and machine vision, providing the
tools needed to transform, analyze, and
visualize images.

Signal Processing Toolbox


The Signal Processing Toolbox in MATLAB is a
powerful collection of functions designed for
analyzing, preprocessing, and manipulating signals.
Signals can come in many forms, such as audio,
biomedical signals, communication signals, and
more. This toolbox provides essential tools for
performing various signal-processing tasks, including
filter design, spectral analysis, time-frequency
analysis, and much more. This section will provide a
comprehensive overview of the Signal Processing
Toolbox, covering its fundamental concepts,
functions, and practical applications.

124
Engineering with MATLAB: A Hands-on Introduction

Why Use the Signal Processing Toolbox?


The Signal Processing Toolbox is essential for
anyone working with signal data because it offers a
wide range of capabilities that facilitate:
• Signal Analysis: Understanding the
characteristics and behavior of signals.
• Signal Enhancement: Improving signal
quality by reducing noise and other unwanted
components.
• Feature Extraction: Identifying and extracting
important features from signals for further
analysis.
• Data Transformation: Converting signals into
different domains (e.g., time to frequency) for
better analysis and interpretation.

The toolbox includes a variety of tools and


functions to address common signal-processing tasks.
Some of the key features include:
• Filter Design and Analysis: Design and analyze
various types of filters, including FIR, IIR,
adaptive, and digital filters.
• Spectral Analysis: Perform Fourier and
wavelet analysis to study the frequency
components of signals.
• Time-Frequency Analysis: Analyze how the
frequency content of a signal changes over
125
Engineering with MATLAB: A Hands-on Introduction

time using methods like the short-time Fourier


transform (STFT) and wavelet transform.
• Signal Measurement: Measure signal
properties such as power, bandwidth, and
distortion.
• Statistical Signal Processing: Apply statistical
methods to signals for noise reduction,
prediction, and classification.

Filter Design and Analysis


Filters are fundamental tools in signal processing,
used to remove unwanted components from signals
or to extract useful information. The Signal
Processing Toolbox provides a variety of functions
for designing and analyzing filters.
1. Finite Impulse Response (FIR) Filters: FIR
filters are widely used because they are
inherently stable and have a linear phase
response. MATLAB provides functions like
fir1, fir2, and firls for designing FIR filters.
2. Infinite Impulse Response (IIR) Filters: IIR
filters can achieve the same filtering effect as
FIR filters with fewer coefficients, making
them computationally efficient. Functions like
butter, cheby1, cheby2, and ellip are available
for designing IIR filters.

126
Engineering with MATLAB: A Hands-on Introduction

3. Filter Analysis: After designing a filter, it is


essential to analyze its frequency response,
phase response, and other characteristics.
Functions like freqz, impz, and grpdelay help
in this analysis.

Example: Designing a Low pass FIR- Filter

order = 50;
cutoff = 0.4;
b = fir1(order, cutoff);
fvtool(b, 1);

Output:

127
Engineering with MATLAB: A Hands-on Introduction

Spectral Analysis
Spectral analysis involves decomposing a signal
into its frequency components. This analysis is
crucial for understanding the frequency behavior of
signals and identifying dominant frequencies.
1. Fourier Transform: The Fourier transform is
a fundamental tool for spectral analysis. The fft
function in MATLAB computes the discrete
Fourier transform (DFT) of a signal, providing
its frequency spectrum.
2. Power Spectral Density (PSD): PSD describes
how the power of a signal is distributed with
frequency. Functions like periodogram,
pwelch, and pyulear estimate the PSD of a
signal.
3. Wavelet Transform: The wavelet transform
provides a time-frequency representation of a
signal, making it suitable for analyzing non-
stationary signals. The cwt function performs
continuous wavelet transform, while dwt
performs discrete wavelet transform.

Example: Computing the FFT of a Signal

128
Engineering with MATLAB: A Hands-on Introduction

% Generate a sample signal


Fs = 1000; % Sampling frequency
t = 0:1/Fs:1-1/Fs; % Time vector
x = sin(2*pi*50*t) + sin(2*pi*120*t);
% Signal with two sinusoidal components
% Compute the FFT
X = fft(x);
N = length(x);
f = (0:N-1)*(Fs/N); % Frequency vector
% Plot the magnitude of the FFT
figure;
plot(f, abs(X));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Magnitude Spectrum');
Output:

129
Engineering with MATLAB: A Hands-on Introduction

Time-Frequency Analysis
Time-frequency analysis techniques are used to
study signals whose frequency content varies over
time. These techniques provide a more detailed view
of the signal's behavior compared to standard spectral
analysis.
1. Short-Time Fourier Transform (STFT): STFT
divides a signal into short segments and applies
Fourier transform to each segment. The
spectrogram function computes and displays
the STFT of a signal.
2. Wavelet Transform: As mentioned earlier,
wavelet transform provides a time-frequency
representation of a signal. It is particularly
useful for analyzing transient and non-
stationary signals.

Example: Computing the Spectrogram of a Signal


% Generate a sample signal
Fs = 1000; % Sampling frequency
t = 0:1/Fs:2-1/Fs; % Time vector
x = chirp(t, 100, 2, 200); % Chirp signal
% Compute the spectrogram
spectrogram(x,256,250,256,Fs,'yaxis');
colorbar;
title('Spectrogram of a Chirp Signal');

130
Engineering with MATLAB: A Hands-on Introduction

Output:

Signal Measurement
The Signal Processing Toolbox provides
functions for measuring various properties of signals,
which are essential for analyzing and interpreting
signal data.
1. Signal Power: The power of a signal indicates
its strength and is computed using the
bandpower function.
2. Bandwidth: The bandwidth of a signal
represents the range of frequencies it occupies.
The obw function calculates the occupied
bandwidth of a signal.
3. Distortion: Distortion measurements help
assess the quality of a signal, especially when it
131
Engineering with MATLAB: A Hands-on Introduction

has undergone some form of processing. The


thd function computes the total harmonic
distortion of a signal.

Example: Measuring Signal Power and


Bandwidth
% Generate a sample signal
Fs = 1000; % Sampling frequency
t = 0:1/Fs:1-1/Fs; % Time vector
x = sin(2*pi*100*t) + 0.5*randn(size(t));
% Signal with noise
p = bandpower(x);
% Compute occupied bandwidth
bw = obw(x, Fs);
% Display results
fprintf('Signal Power: %f W\n', p);
fprintf('Occupied Bandwidth: %f Hz\n',
bw);
Output:

Statistical Signal Processing


Statistical methods are often applied to signals for
various purposes, such as noise reduction, prediction,
and classification. The Signal Processing Toolbox
includes several functions for statistical signal

132
Engineering with MATLAB: A Hands-on Introduction

processing.
1. Noise Reduction: Techniques like moving
average filtering (movmean) and Kalman
filtering (kalman) are used to reduce noise in
signals.
2. Prediction: Predictive modeling of signals can
be performed using autoregressive models (ar
and armax functions).
3. Classification: Signals can be classified into
different categories using machine learning
techniques available in MATLAB.
Example: Applying a Moving Average Filter
% Generate a noisy signal
Fs = 1000; % Sampling frequency
t = 0:1/Fs:1-1/Fs; % Time vector
x = sin(2*pi*50*t) + 0.5*randn(size(t));
% Signal with noise
% Apply a moving average filter
windowSize = 10;
y = movmean(x, windowSize);
% Plot the original and filtered signals
figure;
plot(t, x, t, y);
legend('Original.Signal','Filtered
Signal');
xlabel('Time (s)');
ylabel('Amplitude');
title('Moving Average Filter');
133
Engineering with MATLAB: A Hands-on Introduction

Output:

Practical Applications
The Signal Processing Toolbox is used in a wide
range of applications across various industries:
• Audio Processing: Enhancing audio signals,
noise reduction, and feature extraction for
audio recognition systems.
• Biomedical Signal Processing: Analyzing
ECG, EEG, and other physiological signals for
diagnostic purposes.
• Communication Systems: Designing and
analyzing filters, modulating and
demodulating signals, and assessing signal
quality.
• Seismic Data Analysis: Analyzing earthquake
data, filtering seismic signals.
134
Engineering with MATLAB: A Hands-on Introduction

Image Processing Toolbox


The Image Processing Toolbox in MATLAB is a
comprehensive suite of tools designed for the
analysis and manipulation of images. It is widely used
in various fields such as medical imaging, remote
sensing, computer vision, and more. This toolbox
provides essential functions for image enhancement,
transformation, analysis, and visualization. In this
section, we will explore the Image Processing
Toolbox in detail, covering its key features,
fundamental concepts, and practical applications.

Why Use the Image Processing Toolbox?


The Image Processing Toolbox is essential for
anyone working with image data because it offers a
wide range of capabilities that facilitate:
• Image Enhancement: Improving the quality
and visual appeal of images.
• Image Transformation: Modifying the
geometric and color properties of images.
• Feature Extraction: Identifying and extracting
important image features for further analysis.
• Segmentation: Dividing an image into
meaningful regions for analysis.
• Quantitative Analysis: Measuring and
analyzing specific properties of images.

135
Engineering with MATLAB: A Hands-on Introduction

Key Features of the Image Processing


Toolbox
The toolbox includes various tools and functions
to address common image-processing tasks. Some of
the key features include:
• Image Filtering: Applying various filters to
enhance or modify images.
• Geometric Transformations: Performing
operations such as rotation, scaling, and image
translation.
• Color Space Transformations: Converting
images between different color spaces.
• Image Segmentation: Dividing images into
regions based on specific criteria.
• Morphological Operations: Applying
operations that process images based on their
shapes.
• Image Registration: Aligning images to a
common coordinate system.
• Feature Detection and Extraction: Identifying
and extracting features such as edges, corners,
and blobs.

136
Engineering with MATLAB: A Hands-on Introduction

Image Enhancement
Image enhancement techniques are used to
improve the visual quality of images by highlighting
important features and suppressing noise. The Image
Processing Toolbox provides several functions for
this purpose.
1. Histogram Equalization: This technique
improves the contrast of an image by
spreading out the most frequent intensity
values. The histeq function performs
histogram equalization.
2. Filtering: Various filters can be applied to
smooth, sharpen, or enhance specific features
in an image. Functions like imfilter, fspecial,
and medfilt2 are used for filtering operations.
3. Noise Reduction: Reducing noise in images
can be achieved using functions like wiener2
and imnlmfilt.

Example: Enhancing an Image Using Histogram


Equalization
% Read an image
I = imread('image.jpg');
% Perform histogram equalization
I_eq = histeq(I);
% Display the original and enhanced images
figure;

137
Engineering with MATLAB: A Hands-on Introduction

subplot(1,2,1);
imshow(I);
title('Original Image');
subplot(1,2,2);
imshow(I_eq);
title('Enhanced Image');
Output:

1. Geometric Transformations
Geometric transformations are used to change
the spatial relationship between pixels in an image.
Common geometric transformations include
rotation, scaling, translation, and shearing.
2. Rotation: The imrotate function rotates an
image by a specified angle.
3. Scaling: The imresize function changes the
size of an image.
4. Translation: The imtranslate function shifts an
image by a specified distance.
5. Shearing: The affine2d function creates a
shear transformation matrix that can be
138
Engineering with MATLAB: A Hands-on Introduction

applied using imwarp.

Example: Rotating and Resizing an Image

% Read an image
I = imread('image.jpg');
% Rotate the image by 45 degrees
I_rot = imrotate(I, 45);
% Resize the image to half its original
size
I_resized = imresize(I, 0.5);
figure;
subplot(1,3,1);
imshow(I);
title('Original Image');
subplot(1,3,2);
imshow(I_rot);
title('Rotated Image');
subplot(1,3,3);
imshow(I_resized);
title('Resized Image');
Output:

139
Engineering with MATLAB: A Hands-on Introduction

Color Space Transformations


Images can be represented in different color
spaces, such as RGB, grayscale, HSV, and YCbCr.
Converting between color spaces can be useful for
various image-processing tasks.
1. RGB to Grayscale: The rgb2gray function
converts an RGB image to grayscale.
2. RGB to HSV: The rgb2hsv function converts
an RGB image to the HSV color space.
3. HSV to RGB: The hsv2rgb function converts
an HSV image back to RGB.
4. RGB to YCbCr: The rgb2ycbcr function
converts an RGB image to the YCbCr color
space.

Example: Converting an Image to Different


Color Spaces

% Read an RGB image


I = imread('image.jpg');
% Convert the image to grayscale
I_gray = rgb2gray(I);
% Convert the image to HSV color space
I_hsv = rgb2hsv(I);
% Convert the image to YCbCr color space
I_ycbcr = rgb2ycbcr(I);
figure;
subplot(2,2,1);
140
Engineering with MATLAB: A Hands-on Introduction

imshow(I);
title('Original RGB Image');
subplot(2,2,2);
imshow(I_gray);
title('Grayscale Image');
subplot(2,2,3);
imshow(I_hsv);
title('HSV Image');
subplot(2,2,4);
imshow(I_ycbcr);
title('YCbCr Image');

Output:

141
Engineering with MATLAB: A Hands-on Introduction

Image Segmentation
Image segmentation is the process of dividing an
image into meaningful regions based on specific
criteria, such as color, intensity, or texture.
Segmentation is a critical step in image analysis and
computer vision applications.
1. Thresholding: Thresholding is a simple
method for image segmentation where pixel
values are classified based on a threshold value.
The imbinarize function converts an image to
a binary image using a threshold.
2. Region-Based Segmentation: The
regionprops function measures properties of
image regions. The bwlabel function labels
connected components in a binary image.
3. Edge Detection: The edge function detects
edges in an image using methods like Sobel,
Canny, and Prewitt.
4. Watershed Segmentation: The watershed
function segments an image using the
watershed algorithm.

Example: Segmenting an Image Using


Thresholding

142
Engineering with MATLAB: A Hands-on Introduction

% Read a grayscale image


I = imread('coins.png');
% Convert the image to binary
BW = imbinarize(I);
[B, L] = bwboundaries(BW, 'noholes');
% Display the original and segmented images
figure;
subplot(1,2,1);
imshow(I);
title('Original Image');
subplot(1,2,2);
imshow(label2rgb(L, @jet, [0.5 0.5 0.5]));
title('Segmented Image');

Output:

143
Engineering with MATLAB: A Hands-on Introduction

Morphological Operations
Morphological operations process images based
on their shapes. These operations are particularly
useful for tasks such as noise removal, object
extraction, and shape analysis.
1. Dilation: The imdilate function increases the
size of objects in a binary image.
2. Erosion: The imerode function decreases the
size of objects in a binary image.
3. Opening: The imopen function removes small
objects from an image.
4. Closing: The imclose function fills small holes
in an image.

Example: Applying Morphological Operations

% Read a binary image


BW = imread('cat.png');
% Perform dilation
BW_dilated = imdilate(BW, strel('disk',
3));
% Perform erosion
BW_eroded = imerode(BW, strel('disk', 3));
% Display the original, dilated, and eroded
images
figure;
subplot(1,3,1);
144
Engineering with MATLAB: A Hands-on Introduction

imshow(BW);
title('Original Image');
subplot(1,3,2);
imshow(BW_dilated);
title('Dilated Image');
subplot(1,3,3);
imshow(BW_eroded);
title('Eroded Image');

Output:

Feature Detection and Extraction


Feature detection and extraction involve
identifying and extracting important features from
images, such as edges, corners, and blobs. These
features are crucial for tasks like object recognition,
image matching, and motion tracking.
1. Edge Detection: The edge function detects
edges in an image using various methods like
Sobel, Canny, and Prewitt.

145
Engineering with MATLAB: A Hands-on Introduction

2. Corner Detection: The detectHarrisFeatures


function detects Harris corners in an image.
3. Blob Detection: The detectMSERFeatures
function detects Maximally Stable Extremal
Regions (MSER) in an image

Example: Detecting Edges in an Image

% Read an image
I = imread('cat.png');
% Convert the image to grayscale
I_gray = rgb2gray(I);
% Detect edges using the Canny method
edges = edge(I_gray, 'Canny');
% Display the original and edge-detected
images
figure;
subplot(1,2,1);
imshow(I_gray);
title('Grayscale Image');
subplot(1,2,2);
imshow(edges);
title('Edge-Detected Image');

146
Engineering with MATLAB: A Hands-on Introduction

Output:

Practical Applications
• Medical Imaging: Analyzing medical images
such as X-rays, MRIs, and CT scans for
diagnostic purposes.
• Remote Sensing: Processing satellite and aerial
images for environmental monitoring and
land use analysis.
• Computer Vision: Developing systems for
object detection, facial recognition, and
autonomous navigation.
• Industrial Inspection: Inspecting products for
defects in manufacturing processes.

147
Engineering with MATLAB: A Hands-on Introduction

Toolbox Applications
MATLAB toolboxes are designed to address
specific problems and tasks across a wide range of
fields.
Signal Processing Toolbox
Example 1: Audio Signal Enhancement
In the field of audio signal processing, enhancing
the quality of recorded speech in noisy environments
is a common task. The Signal Processing Toolbox
provides a variety of functions for filtering and
denoising audio signals. For instance, you can use
spectral subtraction methods to remove background
noise from speech recordings, significantly
improving clarity and intelligibility.
• Filtering Techniques: Apply digital filters,
such as FIR and IIR filters, to remove unwanted
noise frequencies.
• Spectral Subtraction: Use techniques to
subtract the estimated noise spectrum from
the noisy speech spectrum.

Example 2: Heart Rate Monitoring


In healthcare, monitoring heart rate variability
using ECG signals is crucial for diagnosing cardiac
conditions. The Signal Processing Toolbox facilitates
this by providing tools for signal preprocessing,
feature extraction, and analysis.
148
Engineering with MATLAB: A Hands-on Introduction

• ECG Signal Preprocessing: Apply filters to


remove baseline wander and noise.
• R-Peak Detection: Use peak detection
algorithms to identify R-peaks in the ECG
waveform.
• Heart Rate Variability Analysis: Calculate
time-domain and frequency-domain
measures to assess heart rate variability.

Image Processing Toolbox


Example 1: Medical Image Analysis
Medical imaging professionals use the Image
Processing Toolbox to enhance and analyze MRI and
CT scans. Techniques such as image segmentation,
edge detection, and morphological operations help in
identifying and delineating tumors or other
anatomical structures.
• Image Enhancement: Improve image contrast
and remove noise using histogram
equalization and filtering techniques.
• Segmentation: Use thresholding, region
growing, and clustering methods to segment
regions of interest, such as tumors.
• Feature Extraction: Extract features like edges,
textures, and shapes for further analysis and
classification.

149
Engineering with MATLAB: A Hands-on Introduction

Example 2: Object Detection in Videos


In computer vision, detecting and tracking
objects in video streams is a common task. The Image
Processing Toolbox provides functions for feature
extraction, object recognition, and tracking.
• Feature Extraction: Detect features like edges,
corners, and blobs in video frames.
• Object Recognition: Use machine learning
algorithms to classify and recognize objects in
video streams.
• Object Tracking: Implement tracking
algorithms, such as Kalman filters and particle
filters, to follow object movement over time.

Extending MATLAB with Add-Ons


MATLAB’s functionality can be further extended
with add-ons, which include additional toolboxes,
user-contributed files, and hardware support
packages. These add-ons can be accessed and
installed via the MATLAB Add-On Explorer, making
it easy to customize and enhance your MATLAB
environment.
Accessing and Installing Add-Ons
1. Open MATLAB: Launch MATLAB and click
on the "Add-Ons" button in the MATLAB
toolstrip.
2. Add-On Explorer: Use the search bar to find
150
Engineering with MATLAB: A Hands-on Introduction

specific add-ons or browse through categories


such as Toolboxes, Apps, Functions, and
Hardware Support Packages.
3. Install Add-Ons: Select the desired add-on and
click the "Install" button. Follow the on-screen
instructions to complete the installation
process.

Types of Add-Ons
• Toolboxes and Apps
These add-ons provide specialized functions and
interactive applications. Examples include the
Robotics System Toolbox for robot modeling and
simulation, and the Financial Toolbox for advanced
financial calculations and risk management.
• Hardware Support Packages
These packages enable MATLAB to interface with
hardware such as Arduino, Raspberry Pi, and various
sensors. This allows for real-time data acquisition and
control applications.
• User-Contributed Files
MATLAB Central hosts a vast collection of user-
contributed files, including custom functions, scripts,
and apps. These files can be downloaded and
integrated into your MATLAB environment to
extend its functionality.

151
Engineering with MATLAB: A Hands-on Introduction

Creating and Sharing Your Add-Ons


If you develop custom functions or apps that
could benefit others, you can share them on
MATLAB Central. Use the
matlab.addons.toolbox.packageToolbox function to
package your add-on and upload it to MATLAB
Central File Exchange, providing a detailed
description and usage instructions.

MATLAB toolboxes and add-ons significantly


enhance MATLAB's capabilities, allowing users to
perform complex tasks efficiently and accurately.
From signal processing to image analysis and
optimization, the specialized functions provided by
these toolboxes are invaluable for a wide range of
applications. Understanding how to install and use
these toolboxes, as well as how to extend MATLAB
with additional add-ons, enables users to fully
leverage the power of MATLAB. Whether you are
analyzing signals, processing images, or solving
optimization problems, MATLAB's extensive toolbox
ecosystem provides the tools you need to succeed.

152
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 8

DEBUGGING AND
TROUBLESHOOTING
Debugging and troubleshooting are essential
components of the programming process in
MATLAB, ensuring that your code functions as
intended and produces accurate results. This chapter
explores common errors and warnings, debugging
techniques, and tips for efficient debugging. The goal
is to equip you with the knowledge and skills needed
to effectively identify and resolve issues in your
MATLAB code.
Understanding the nature of common errors and
warnings in MATLAB is crucial for efficient
debugging. Errors can generally be classified into
three categories: syntax errors, runtime errors, and
logical errors. Additionally, warnings, while not as
severe as errors, provide important insights into
potential issues within your code.

153
Engineering with MATLAB: A Hands-on Introduction

Syntax Errors
Syntax errors occur when the MATLAB
interpreter encounters code that it cannot
understand. These errors are often the result of
typographical mistakes, incorrect punctuation, or
misuse of MATLAB’s syntax. The MATLAB editor
provides real-time feedback on syntax errors,
highlighting problematic lines of code and suggesting
corrections. Familiarizing yourself with MATLAB’s
syntax and using the integrated editor’s feedback can
help minimize these errors.
Runtime Errors
Runtime errors arise during the execution of a
script or function. Unlike syntax errors, which are
detected before execution, runtime errors occur due
to operations that are mathematically or logically
invalid. Common causes include division by zero,
accessing elements outside the bounds of an array, or
performing operations on incompatible data types.
Addressing runtime errors requires careful review of
the code’s logic and the conditions under which the
errors occur.
Logical Errors
Logical errors are the most insidious, as they do
not produce error messages but result in incorrect
outputs due to flawed logic in the code. These errors
require meticulous testing and verification of the
154
Engineering with MATLAB: A Hands-on Introduction

program’s output against expected results.


Implementing comprehensive test cases and
validating results at various stages of the code can
help identify and correct logical errors.
Warnings
Warnings in MATLAB signal potential issues that
do not halt the program’s execution but indicate areas
where improvements or corrections may be
necessary. While warnings do not prevent the code
from running, addressing them can enhance the
robustness and reliability of your code. MATLAB’s
warning messages often include suggestions for
resolving the underlying issues, making them a
valuable resource for code optimization.
Debugging Techniques
Effective debugging techniques are essential for
identifying and resolving errors in MATLAB code.
The following methods and tools can assist in
systematically debugging your programs.
• Breakpoints
Breakpoints are one of the most powerful tools
for debugging in MATLAB. By setting breakpoints at
strategic locations in your code, you can pause
execution and examine the state of variables at
specific points. This allows you to verify that your
code is functioning as expected up to that point.
Breakpoints can be set by clicking in the margin next
155
Engineering with MATLAB: A Hands-on Introduction

to the line number in the MATLAB editor or by using


the dbstop function in the command window.
• Step-by-Step Execution
Step-by-step execution enables you to execute
your code one line at a time, observing the effect of
each line on the program’s state. This method is
particularly useful for tracing the flow of execution
and identifying where logical errors or unexpected
behavior occur. MATLAB provides commands like
dbstep to step through the code and dbcont to
continue execution until the next breakpoint.
• Variable Inspection
Inspecting the values of variables at different
stages of execution is crucial for understanding the
program’s behavior. MATLAB’s workspace and
variable editor allow you to view and modify the
values of variables during a debugging session.
Additionally, commands like whos and disp can be
used to display variable information in the command
window.
• Diagnostic Output
Inserting diagnostic output statements, such as
disp or fprintf, throughout your code can provide
insights into the program’s execution flow and the
values of variables at specific points. While this
method is less sophisticated than breakpoints or step-
by-step execution, it can be useful for quickly
156
Engineering with MATLAB: A Hands-on Introduction

identifying issues in smaller scripts or functions.


• Error and Warning Messages
Paying attention to MATLAB’s error and warning
messages is essential for effective debugging. These
messages often contain detailed information about
the nature and location of the error, along with
suggestions for resolution. Reviewing the full text of
error messages and following any provided guidance
can expedite the debugging process.
• Try-Catch Blocks
Using try-catch blocks allows you to handle errors
gracefully and continue execution even when an
error occurs. This technique is particularly useful for
debugging larger programs where you want to isolate
and address errors without disrupting the entire
workflow. Within a catch block, you can implement
error-handling logic or display diagnostic
information to aid in debugging.

Tips for Efficient Debugging


Efficient debugging requires a systematic
approach and the effective use of MATLAB's
debugging tools. Here are some tips to help you
debug more efficiently:
1. Understand Error Messages: Carefully read
and interpret MATLAB's error messages. They
often contain valuable information about the
157
Engineering with MATLAB: A Hands-on Introduction

nature and location of the problem.


2. Isolate the Problem: Narrow down the section
of code where the error occurs by commenting
out parts of the code or using breakpoints.
3. Use Descriptive Names: Use clear and
descriptive variable and function names to
make your code easier to read and debug.
4. Check Intermediate Results: Insert temporary
display statements (e.g., disp, fprintf) to check
the values of variables at various stages in your
code.
5. Test with Simple Inputs: Validate your code
with simple, known inputs before testing with
more complex data to ensure basic
functionality.
6. Modularize Your Code: Break your code into
smaller, manageable functions. This makes it
easier to isolate and test individual
components.
7. Document Your Code: Include comments and
documentation to explain the purpose and
logic of your code. This is invaluable when you
need to debug or modify your code later.
8. Use Version Control: Implement version
control (e.g., Git) to keep track of changes and
easily revert to previous versions if necessary.
9. Leverage MATLAB Documentation: Consult
158
Engineering with MATLAB: A Hands-on Introduction

MATLAB's extensive documentation and


online resources for guidance on specific
functions and error messages.
10. Peer Review: Have your code reviewed by
peers. A fresh pair of eyes can often spot errors
that you might have overlooked.

By understanding common errors and warnings,


employing effective debugging techniques, and
following best practices, you can significantly
improve the reliability and performance of your
MATLAB programs. Debugging is an iterative
process that involves careful analysis, testing, and
refinement. Mastery of these skills will enhance your
overall programming proficiency and contribute to
the development of robust and error-free code.

159
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 9

INTRODUCTION TO
SIMULINK
Simulink is an integral part of the MATLAB
ecosystem, providing a robust environment for
modeling, simulating, and analyzing dynamic
systems. Building on the previous chapter where we
discussed extending MATLAB's functionality with
various toolboxes, Simulink can be seen as an
essential extension that enhances your ability to
visualize and simulate complex systems. In this
chapter, we will learn the basics of Simulink,
including an introduction to its features and
capabilities, as well as a detailed guide on creating
Simulink models.
Simulink is a powerful simulation and model-
based design environment that extends MATLAB's
capabilities. It offers a graphical user interface (GUI)
where users can build models as block diagrams,
making it easier to visualize the interaction between
different components of a system. Simulink supports
a wide range of applications, from control systems
and signal processing to communications and image
processing.
160
Engineering with MATLAB: A Hands-on Introduction

Simulink’s interface allows users to drag and drop


blocks from a library into a workspace, connect them
with lines to define signal flow, and configure their
parameters to accurately represent the system being
modeled. This block diagram approach simplifies the
modeling process and makes it accessible even to
those who may not be as comfortable with traditional
programming.

Key Features of Simulink:


1. Interactive Graphical Environment: Simulink
provides an intuitive GUI for creating block
diagrams, making it easy to visualize and
understand complex systems.
2. Comprehensive Block Libraries: Simulink
includes extensive libraries of pre-built blocks
for various applications, such as signal
processing, control systems, and
communications. These blocks can be
customized to fit specific needs.
3. Integration with MATLAB: Simulink
seamlessly integrates with MATLAB, allowing
users to utilize MATLAB functions, scripts, and
toolboxes within Simulink models. This
integration enhances the modeling capabilities
and provides a powerful environment for
161
Engineering with MATLAB: A Hands-on Introduction

simulation and analysis.


4. Support for Multidomain Modeling:
Simulink allows for the modeling of systems
that involve multiple domains, such as
electrical, mechanical, and hydraulic systems,
within a single environment.
5. Simulation and Analysis Tools: Simulink
provides tools for running simulations,
analyzing results, and tuning model
parameters. Users can simulate the behavior of
their systems over time and under different
conditions to gain insights into their
performance.
6. Code Generation: Simulink supports
automatic code generation, allowing users to
generate C, C++, or HDL code from their
models. This feature is particularly useful for
rapid prototyping and deploying models to
embedded systems.

Creating Simulink Models


Creating a Simulink model involves several steps,
from defining the system to running simulations and
analyzing the results.
1. Starting Simulink: Open MATLAB and click
on the Simulink icon in the MATLAB toolbar
or type simulink in the MATLAB command
162
Engineering with MATLAB: A Hands-on Introduction

window. This action opens the Simulink Start


Page, where you can create a new model or
open an existing one.

2. Creating a New Model: From the Simulink


Start Page, click on "Blank Model" to create a
new, empty Simulink model. This opens a new
window with an empty canvas where you can
begin building your model.
3. Adding Blocks: The Simulink Library Browser
contains a wide variety of blocks organized
into libraries. These libraries include sources,
sinks, math operations, continuous and
discrete dynamics, and many others. Drag and
drop blocks from the Library Browser into the
model canvas to construct your model.
For instance, to build a basic model, you might
start with a "Sine Wave" block from the

163
Engineering with MATLAB: A Hands-on Introduction

Library Browser, a "Gain" block and a "Scope".

5. Connecting Blocks: Connect the blocks by


clicking on the output port of one block and
dragging it to the input port of another block.
This defines the signal flow in your model. For
example, connect the output of the Sine Wave
block to the input of the Gain block, and then
connect the output of the Gain block to the
Scope.

6. Configuring Block Parameters: Double-click


on each block to open its parameter dialog.
Here, you can configure the specific
parameters of the block, such as the frequency
and amplitude of the Sine Wave, or the gain
164
Engineering with MATLAB: A Hands-on Introduction

value of the Gain block.


7. Running the Simulation: Once your model is
constructed, you can simulate it by clicking the
"Run" button on the Simulink toolbar.
Simulink will simulate the behavior of your
system over the specified time period. You can
adjust the simulation parameters, such as start
and stop times, from the model configuration
parameters.
8. Analyzing Results: After running the
simulation, you can analyze the results using
the tools provided by Simulink. The Scope
block, for example, displays the output signal
over time, allowing you to visualize the
system's behavior. Additionally, you can
export simulation data to MATLAB for further
analysis using MATLAB scripts and functions.
9. Saving and Documenting the Model: Save
your model by selecting "Save" from the File
menu or by pressing Ctrl+S. It's also good
practice to document your model by adding
annotations and descriptions. This helps others
understand the purpose and functionality of
your model.

165
Engineering with MATLAB: A Hands-on Introduction

Exploring Demo Models in Simulink


Simulink provides a variety of demo models that
are an excellent resource for learning more about the
software's capabilities. These models are pre-built
examples that showcase different functionalities and
techniques, allowing users to explore and understand
complex systems without starting from scratch.

Accessing Demo Models


1. MATLAB Command Window:
o Open MATLAB and go to the Command
Window.
o Type demo and press Enter. This will
open the MATLAB and Simulink
example browser.
o In the example browser, you can filter
the examples by product, such as
Simulink, to find relevant demos.
2. Simulink Start Page:
o Open Simulink by typing simulink in
the MATLAB Command Window or by
clicking the Simulink icon.
o On the Simulink start page, click on the
"Examples" tab. This will direct you to a
collection of example models
categorized by different applications
and functionalities.
166
Engineering with MATLAB: A Hands-on Introduction

Using Demo Models


1. Browse and Select:
o Browse through the various categories
such as control systems, signal
processing, communications, and more.
o Select a demo model that matches your
interest or learning objective.
2. Open and Explore:
o Click on the demo model to open it in
Simulink. The model will be displayed
in a new Simulink window.
o Explore the model to understand how it
is built. Look at the various blocks,
connections, and parameters used.
3. Run Simulations:
o Once you have opened a demo model,
you can run the simulation by clicking
the Run button on the toolbar.
o Observe the outputs and the behavior of
the model in the Scope or other
visualization blocks used in the demo.
4. Modify and Experiment:
o To deepen your understanding, try
modifying the parameters, adding new
blocks, or changing the connections in
the demo model.
167
Engineering with MATLAB: A Hands-on Introduction

o Experiment with different


configurations to see how they affect the
system’s performance.
5. Read Documentation:
o Each demo model usually comes with
detailed documentation explaining the
purpose of the model, the theory behind
it, and step-by-step instructions on how
to use it.
o Access the documentation by clicking on
the Help menu or the Model Info block
within the demo model.

Example of Demo Models


• Control System Examples:
o Explore models related to PID control,
state-space control, and more.
o Learn how to design and simulate
control systems using Simulink blocks.
• Signal Processing Examples:
o Find models that demonstrate filtering,
Fourier transforms, and other signal
processing techniques.
o Understand how to process and analyze
signals using the Signal Processing
Toolbox.

168
Engineering with MATLAB: A Hands-on Introduction

• Automotive Examples:
o Explore models related to vehicle
dynamics, powertrain, and hybrid
electric vehicles.
o Learn about automotive applications
and how to simulate them using
Simulink.

Advantages:
• Hands-on Learning: Demo models provide a
practical way to learn Simulink by seeing how
real-world systems are modeled and
simulated.
• Save Time: Instead of starting from scratch,
you can use demo models as a starting point
and modify them according to your needs.
• Gain Insights: By studying well-constructed
models, you can gain insights into best
practices and advanced techniques used by
experienced users.
• Interactive Exploration: Experimenting with
demo models allows you to interactively
explore different scenarios and understand the
impact of various parameters and
configurations.

169
Engineering with MATLAB: A Hands-on Introduction

CHAPTER 10

SIMULATING
SIMULINK MODELS
Simulating models in Simulink is a fundamental
step for analyzing and understanding the behavior of
dynamic systems. This chapter provides a detailed
process for simulation setup, running simulations,
interpreting results, and troubleshooting common
issues. This is the final chapter of this book, and we
will provide a comprehensive overview, while more
advanced topics will be explored in the next volume.

Simulation Setup
Proper configuration of the model is essential
before running a simulation. This involves setting up
solver options, defining simulation parameters, and
ensuring that all model components are accurately
specified.
Configuring Solver Options
Simulink uses solvers to perform numerical
integration of the differential equations that describe
the model. The choice of solver can significantly
impact the accuracy and efficiency of the simulation.
To access the solver configuration:
170
Engineering with MATLAB: A Hands-on Introduction

1. Open the Simulink model.


2. Navigate to the Simulation menu and select
Model Configuration Parameters.
3. In the Configuration Parameters dialog box,
find the Solver pane.
Choosing the right solver involves understanding
the types available. Solvers are classified into two
main types: fixed-step and variable-step. Fixed-step
solvers are typically used for real-time applications,
whereas variable-step solvers are suited for high-
accuracy simulations. Common solvers include
ode45 (Dormand-Prince), ode15s (Stiff/NDF), and
ode1 (Euler).
Defining Simulation Parameters
Simulation parameters include the start and stop
times, step size, and other settings that control the
simulation's execution.
Setting simulation time involves specifying the
Start time and Stop time under the Solver pane. This
defines the simulation's duration. Choosing an
appropriate stop time is crucial to capture the
system's behavior of interest. For fixed-step solvers,
specify the Fixed-step size. Smaller step sizes improve
accuracy but increase computational effort, while
variable-step solvers adjust the step size dynamically
based on the model's behavior.

171
Engineering with MATLAB: A Hands-on Introduction

4. Running Simulations
Once the setup is complete, running a simulation
involves executing the model to generate output data
and visualize system dynamics.
Starting the simulation is straightforward. Click
the Run button on the Simulink toolbar to begin the
simulation using the specified parameters. Monitor
the Simulation Diagnostics window for any warnings
or errors that may occur during the simulation.
Visualizing results is crucial for interpreting the
data. Use scopes and other visualization blocks to
view the simulation output in real-time. Data can also
be logged to the MATLAB workspace for further
analysis and post-processing.

172
Engineering with MATLAB: A Hands-on Introduction

5. Interpreting Results
Understanding the results of a simulation is
crucial for validating the model and drawing
meaningful conclusions.
Analyzing scope outputs involves examining the
graphical representation of signal values over time.
Look for patterns, oscillations, and steady-state
behavior in these waveforms. Adjust the scope
settings to optimize the display, including axes, grid,
and other properties.
Data logging stores simulation data in the
MATLAB workspace. Use MATLAB functions such as
plot, histogram, and statistical analyses (mean, std, fft)
to interpret this data.
Troubleshooting Common Issues
Simulations can encounter various issues, such as
numerical instability, solver errors, or unexpected
results. Here are some common problems and their
solutions:

1. Numerical Instability:
o If the simulation behaves erratically, try
reducing the step size for fixed-step
solvers or switch to a more robust
variable-step solver.
o Ensure model parameters and initial
conditions are physically realistic.

173
Engineering with MATLAB: A Hands-on Introduction

2. Solver Errors:
o Solver errors may indicate stiff
dynamics or discontinuities in the
model. Use stiff solvers like ode15s to
handle these cases.
o Check for algebraic loops, as they can
cause convergence issues. Eliminate
them if possible.
3. Unexpected Results:
o Verify that model equations and
parameters accurately represent the
system.
o Use the Model Advisor tool to check for
common modeling issues and best
practice violations.

Tips for Efficient Simulation


Optimizing your simulation involves finding a
balance between accuracy and computational
efficiency.
Model Simplification:
Simplify the model by removing unnecessary
components and combining similar elements. This
reduces computational load and improves simulation
speed. Use subsystems to modularize the model,
making it more readable and manageable.

174
Engineering with MATLAB: A Hands-on Introduction

Parameter Tuning:
Experiment with different solver options and
settings to find the best configuration for your model.
Use parameter sweeps and optimization tools to
automate the tuning process.
Code Generation:
For long-running simulations, consider
generating C code from your Simulink model using
Simulink Coder. This can significantly speed up the
simulation. The generated code can be run outside
MATLAB, enabling deployment in real-time
applications.
6. Testing with Demo Models
Simulink provides a variety of demo models that
you can use to learn more about simulation
techniques and best practices. These models cover
different domains and applications, providing hands-
on experience with pre-built examples.
To access demo models:
1. Go to the Help menu in Simulink and select
Examples.
2. Browse through the available demo models
and select one that matches your area of
interest.
Studying demo models helps you understand
their setup, components, and simulation parameters.

175
Engineering with MATLAB: A Hands-on Introduction

By following these detailed steps and best


practices, you can effectively simulate and analyze
dynamic systems using Simulink. This chapter has
provided a comprehensive guide to setting up,
running, and interpreting simulations, ensuring that
you can leverage the full capabilities of Simulink for
your projects. The next volume of this series will
explore more advanced topics, offering deeper
insights into Simulink's powerful features and
applications.

176
Engineering with MATLAB: A Hands-on Introduction

Conclusion
As we conclude this guide on MATLAB, we hope that
you have found this book to be an invaluable resource
in your journey to mastering one of the most
powerful tools in scientific computing and
engineering. From the basics of vectors and matrices
to the complexities of Simulink models, we have
covered a broad spectrum of topics designed to equip
you with the knowledge and skills needed to leverage
MATLAB to its fullest potential.
Throughout this book, we have emphasized practical
applications and real-world examples to demonstrate
how MATLAB can be used to solve a wide range of
problems. Whether you are a student, researcher, or
professional, the concepts and techniques outlined in
these pages aim to enhance your analytical
capabilities and improve your efficiency in handling
data, performing simulations, and visualizing results.
Key Takeaways
• Understanding MATLAB Fundamentals: We
started with the basics, ensuring a solid
foundation in MATLAB's syntax and primary
functions. This grounding is crucial for anyone
looking to investigate deeper into more
complex applications.

177
Engineering with MATLAB: A Hands-on Introduction

• Advanced Data Handling and Visualization:


We explored various methods of importing,
preprocessing, and analyzing data. The
sections on data visualization aimed to show
you how to present your data in the most
meaningful and visually appealing ways.
• Efficient Programming Practices: Writing
efficient code is essential in any programming
environment. The best practices and
debugging techniques we discussed will help
you write clean, maintainable, and error-free
code.
• Toolbox Proficiency: The specialized
toolboxes are what make MATLAB
exceptionally powerful. Our detailed coverage
of the Signal Processing, Image Processing,
Optimization, and Machine Learning
Toolboxes provided you with the tools to
tackle specific problems in these domains.
• Simulink and Model-Based Design: Finally,
the introduction to Simulink and model-based
design opened up a new dimension of
possibilities for simulating and analyzing
dynamic systems.

178
Engineering with MATLAB: A Hands-on Introduction

Looking Ahead
MATLAB is a constantly evolving platform with
continuous updates and new features being added
regularly. As you progress in your career or studies,
staying updated with the latest developments and
exploring new toolboxes and functions will be
beneficial. The skills and knowledge you have gained
from this book will serve as a strong foundation for
further learning and exploration.
Final Thoughts
The power of MATLAB lies not only in its extensive
library of functions and toolboxes but also in its
ability to bring clarity and insight to complex data
and systems. As you continue to use MATLAB, you
will discover new ways to apply its capabilities to your
unique challenges, driving innovation and efficiency
in your work.
We thank you for boarding on this journey with us
and wish you continued success in all your MATLAB
endeavors. Remember, the key to mastering
MATLAB, like any other skill, is practice and
continuous learning. Use this book as your guide and
reference, and don't hesitate to explore beyond its
pages.
Happy coding!
Dr. Jagadish Tawade
Nitiraj Kulkarni
179

You might also like