Simulation Laboratory
Simulation Laboratory
VISION
MISSION
To provide all necessary inputs to the students for them to grow into
knowledge engineers and scientists attaining.
Prepared by
1
INDEX
SL
NAME OF THE EXPERIMENT Page No.
.No.
CREATE AND MANIPULATE THE VARIABLES FOR TEXT AND NUMERIC DATA
3 40
TYPES
IMPORT AND EXPORT DATA AS TEXT FILES, SPREADSHEETS, OTHER FILE
4 52
FORMATS AND WEB ACCESS
CREATE VARIABLES WITHIN /IMPORT INTO WORKSPACE OF MATLAB
5 57
FROM DATA FILES OR OTHER PROGRAMS
BASIC PROGRAMS IN SCRIPTS CONTAINING SEQUENCE OF COMMANDS
6 63
AND FUNCTIONS
BASIC PROGRAMS USING LOOPS AND CONDITIONAL STATEMENTS, SUCH
7 69
AS IF, FOR, AND WHILE
SOLVING MATHEMATICAL FUNCTIONS USING COMPUTATIONAL
8 75
SOFTWARE
SOLVING MATRICES AND VECTORS PROBLEMS USING COMPUTATIONAL
9 80
SOFTWARE
CREATE 2D,3D PLOTS AND DISPLAY IT IN GRAPHICAL WINDOW USING
10 86
COMPUTATIONAL SOFTWARE
2
Contents
1. COMPONENTS OF COMPUTATIONAL SOFTWARE AND TOOLBOXES .................................... 4
1.1 Commands that create variables and call functions: ................................................................. 5
1.2 Workspace Variables: ............................................................................................................... 6
1.3 Calling Functions:...................................................................................................................... 7
1.4 Simulink: ................................................................................................................................... 8
1.4.1. Simulink Block Diagrams: ................................................................................................. 8
1.4.2. Create a Simple Model: ................................................................................................... 11
1.4.3 Open New Model ............................................................................................................. 12
1.4.4 Open Simulink Library Browser ........................................................................................ 13
1.4.5 Add Blocks to a Model ..................................................................................................... 15
1.4.6 Connect Blocks ................................................................................................................ 16
1.4.7 Refine Model .................................................................................................................... 18
1.5. TOOLBOX’s In MATLAB ........................................................................................................ 24
2. MATHEMATICAL OPERATIONS USING ARRAYS AND MATRICES .......................................... 30
2.1. Array Creation ........................................................................................................................ 30
2.2. Matrix and Array Operations .................................................................................................. 31
2.3 Constructing a Matrix of Data .................................................................................................. 35
2.4 Specialized Matrix Functions................................................................................................... 35
2.5 Concatenating Matrices .......................................................................................................... 36
2.6 Expanding a Matrix ................................................................................................................. 38
3. CREATE AND MANIPULATE THE VARIABLES FOR TEXT AND NUMERIC DATA TYPES ...... 40
Implicit Expansion....................................................................................................................... 44
4. IMPORT AND EXPORT DATA AS TEXT FILES, SPREADSHEETS, OTHER FILE ..................... 52
5. CREATE VARIABLES WITHIN /IMPORT INTO WORKSPACE OF MATLAB FROM DATA FILES
OR OTHER PROGRAMS ................................................................................................................. 57
6. BASIC PROGRAMS IN SCRIPTS CONTAINING SEQUENCE OF COMMANDS AND
FUNCTIONS ..................................................................................................................................... 63
Run Code ................................................................................................................................... 67
7. BASIC PROGRAMS USING LOOPS AND CONDITIONAL STATEMENTS, SUCH AS IF, FOR,
AND WHILE ...................................................................................................................................... 69
9. SOLVING MATRICES AND VECTORS PROBLEMS USING COMPUTATIONAL SOFTWARE .. 80
10. CREATE 2D,3D PLOTS AND DISPLAY IT IN GRAPHICAL WINDOW USING
COMPUTATIONAL SOFTWARE ...................................................................................................... 86
11. DESIGN A SIMPLE DIGITAL CIRCUITS (ADDER) USING SIMULINK ...................................... 90
12. APP DESIGNER USING MATLAB .............................................................................................. 92
APPENDIX 1: MATLAB Installation Guide ........................................................................................ 95
Account Creation:.......................................................................................................................... 95
Steps to Install MATLAB: .............................................................................................................. 96
APPENDIX 2: Self-Paced, Online Training for MATLAB and Simulink ............................................. 98
Steps to Access the MATLAB Training Courses: .......................................................................... 98
Product List R2020b...................................................................................................................... 99
3
1. COMPONENTS OF COMPUTATIONAL SOFTWARE AND
TOOLBOXES
AIM:
To acquire knowledge on the basic components available in the MATLAB and explore the
toolbox’s which are used for various applications.
DESCRIPTION
In this experiment, the basic functions of MATLAB are discussed. The practice exercises
familiarize the MATLAB environments, like file accessing, creating variables, command line
input and output, script file creation and execution and Simulink file creation and execution.
Desktop Basics:
The MATLAB desktop appears in its default layout as shown Fig 1.1.
PRACTICE EXERCISES:
>> a = 1
MATLAB adds variable ‘a’ to the workspace and displays the result in the Command Window.
>> a = 1
>> b = 2
b= 2
>> c = a + b
c= 3
>> d = cos(a)
d = 0.5403
When you do not specify an output variable, MATLAB uses the variable ans, short
for answer, to store the results of your calculation.
>> sin(a)
ans = 0.8415
If you end a statement with a semicolon, MATLAB performs the computation, but
suppresses the display of output in the Command Window.
>> e = a*b;
You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓.
Press the arrow keys either at an empty command line or after you type the first few
characters of a command.
For example, to recall the command b = 2, type b, and then press the up-arrow key.
5
1.2 Workspace Variables:
The workspace contains variables that you create within or import into MATLAB® from
data files or other programs. For example, these statements create variables A and B in the
workspace.
>> A = magic(4);
>> B = rand(3,5,2);
You can view the contents of the workspace using whos.
>> whos
Name Size Bytes Class Attributes
A 4x4 128 double
B 3x5x2 240 double
The variables also appear in the Workspace pane on the desktop as shown Fig 1.2
Workspace variables do not persist after you exit MATLAB. Save your data for later use
with the save command,
save myfile.mat
Saving preserves the workspace in your current working folder in a compressed file with
a .mat extension, called a MAT-file.
To clear all the variables from the workspace, use the clear command.
load myfile.mat
6
1.3 Calling Functions:
MATLAB® provides a large number of functions that perform computational tasks. Functions
are equivalent to subroutines or methods in other programming languages.
>> A = [1 3 5];
>> max(A)
ans = 5
If there are multiple input arguments, separate them with commas:
When there are multiple output arguments, enclose them in square brackets:
>> clc
The clc function clears the Command Window.
7
1.4 Simulink:
Simulink® is a block diagram environment for multidomain simulation and Model-Based
Design. It supports system-level design, simulation, automatic code generation, and continuous
test and verification of embedded systems. Simulink provides a graphical editor, customizable
block libraries, and solvers for modeling and simulating dynamic systems. It is integrated with
MATLAB®, enabling you to incorporate MATLAB algorithms into models and export simulation
results to MATLAB for further analysis.
A faucet fills a bucket — Water goes into the bucket at a certain flow rate, and the bucket
gets heavier. A block can represent the bucket, with flow rate as the input and its weight as
the output.
You use a megaphone to make your voice heard — The sound produced at one end of the
megaphone is amplified at the other end. The megaphone is the block, the input is the sound
wave at its source, and the output is the sound wave as you hear it.
You push a cart and it moves — The cart is the block, the force you apply is the input, and
the cart's position is the output.
The definition of a block is only complete with its inputs and outputs defined; this task
relates to the goal of the model. For example, the cart velocity may be a natural choice as an output
if the modeling goal does not involve its location.
Simulink provides block libraries that are collections of blocks grouped by functionality.
For example, to model a megaphone that multiplies its input by a constant, you use a Gain block
from the Math Operations library.
8
Fig 1.3 Gain block in the MATLAB Simulink
A sound wave goes into the megaphone as its input, and a louder version of the same wave
comes out as its output. The > signs denote the inputs and outputs of a block, which can be
connected to other blocks.
You can connect blocks to other blocks to form systems and represent more complex
functionality. For example, an audio player turns a digital file into sound. A digital representation
is read from storage, is interpreted mathematically, and then turned into physical sound. The
software that processes the digital file to compute the sound waveform can be one block; the
speaker that takes the waveform and turns it into sound can be another block. A component that
generates the input is another block.
The primary function of Simulink is to simulate behavior of system components over time.
In its simplest form, this task involves keeping a clock, determining the order in which the blocks
are to be simulated, and propagating the outputs computed in the block diagram to the next block.
Consider the megaphone.
9
Fig 1.6 Simulink file, amplifies the input for each second
At each time step, each block computes its outputs from its inputs. Once all of the signals
in a diagram are computed at a given time step, Simulink determines the next time step (based on
the model configuration and numerical solver algorithms) and advances the simulation clock.
Fig 1.7 Simulink file, amplifies the input for every 2 seconds
In simulation, time progresses differently from a real clock. Each time step takes as much
time as it takes to finish the computations for that time step, whether that time step represents a
fraction of a second or a few years.
Often, the effect of a component's input on its output is not instantaneous. For example,
turning on a heater does not result in an instant change in temperature. Rather, this action provides
input to a differential equation. The history of the temperature (a state) is also a factor. When
simulation requires solving a differential or difference equation, Simulink employs memory and
numerical solvers to compute the state values for the time step.
10
Simulink handles data in three categories:
States - Internal values, representing the dynamics of the block, computed during
simulation
Parameters - Values that affect the behavior of a block, controlled by the user
At each time step, Simulink computes new values for signals and states. By contrast, you
specify parameters when you build the model and can occasionally change them while simulation
is running.
A Simulink block is a model element that defines a mathematical relationship between its
input and output. To create this simple model, you need four Simulink blocks as shown in Table I
11
Fig 1.8 Simple Simulink model to process the pulse signal
Simulating this model integrates a brief pulse twice to get a ramp. The results display in a Scope
window. The input pulse represents a press of the gas pedal — 1 when the pedal is pressed and 0
when it is not. The output ramp is the increasing distance from the starting point.
1. Start MATLAB®. From the MATLAB toolstrip, click the Simulink button .
3. From the Simulation tab, select Save > Save as. In the File name text box, enter a name for
your model. For example, simple_model. Click Save. The model is saved with the file
extension .slx.
Sinks — Blocks that store and show the signals that connect to them
Sources — Blocks that generate the signal values that drive the model
13
1. From the Simulation tab, click the Library Browser button
2. Set the Library Browser to stay on top of the other desktop windows as shown in Fig 1.11. On
the Simulink Library Browser toolbar, select the Stay on top button .
To browse through the block libraries, select a category and then a functional area in the left
pane. To search all of the available block libraries, enter a search term.
Fig 1.12 MATLAB Simulink library shows search result for ‘pulse’ signal
14
For example, find the Pulse Generator block. In the search box on the browser toolbar,
enter pulse, and then press Enter. Simulink searches the libraries for blocks with pulse in their
name or description and then displays the blocks.
Get detailed information about a block. Right-click the Pulse Generator block, and then
select Help for the Pulse Generator block. The Help browser opens with the reference page for
the block.
Blocks typically have several parameters. You can access all block parameters by double-
clicking the block.
1. From the Sources library, drag the Pulse Generator block to the Simulink Editor. A copy
of the Pulse Generator block appears in your model with a text box for the value of
the Amplitude parameter. Enter 1.
1. Add the following blocks as shown in Table 1.2 to your model using the same approach.
2. Add a second Outport block by copying the existing one and pasting it at another point
using keyboard shortcuts.
15
4. Arrange the blocks by clicking and dragging each block as shown in Fig 1.14. To resize a
block, drag a corner.
Fig 1.13 MATLAB Simulink blocks for ‘pulse’ signal Simulink model
1. Click the output port on the right side of the Pulse Generator block.
The output port and all input ports suitable for a connection are highlighted as shown in Fig
1.14.
Simulink connects the blocks with a line and an arrow indicating the direction of signal flow
as shown in Fig 1.15.
Fig 1.15 Pulse signal block and Gain block ports are connected
3. Connect the output port of the Gain block to the input port on the Integrator, Second-
Order block.
4. Connect the two outputs of the Integrator, Second-Order block to the two Outport blocks.
5. Save your model. In the Simulation tab, click the Save button.
16
Fig 1.16 Final simulation program for pulse signal generation
Click the signal. In the Simulation tab under Prepare, click Add Viewer. Select Scope. A viewer
icon appears on the signal as shown in the Fig 1.17 and a scope window opens.
You can open the scope at any time by double-clicking the icon.
Run Simulation
After you define the configuration parameters, you are ready to simulate your model.
1. In the Simulation tab, set the simulation stop time by changing the value in the toolbar as
shown in Fig 1.18.
The default stop time of 10.0 is appropriate for this model. This time value has no unit. The
time unit in Simulink depends on how the equations are constructed. This example simulates
the simplified motion of a car for 10 seconds — other models could have time units in
milliseconds or years.
The simulation runs and produces the output in the viewer as shown in Fig 1.19.
17
Fig 1.19 Scope window showing output of the simulation
In the physical world, a sensor measures the distance imprecisely, causing random
numerical errors.
To start, open the moving_car model. At the MATLAB command line, enter:
18
Fig 1.20 Simulink model opened through MATLAB command
You first need to model the hard stop when the car position reaches 10 . The Integrator, Second-
Order block has a parameter for that purpose.
1. Double-click the Integrator, Second-Order block. The Block Parameters dialog box appears.
2. Select Limit x and enter 10 for Upper limit x. The background color for the parameter changes
to indicate a modification that is not applied to the model. Click OK to apply the changes and
close the dialog box.
1. Modify the model. Expand the model window to accommodate the new blocks as necessary.
Find the actual distance. To find the distance between the obstacle position and the vehicle
position, add the Subtract block from the Math Operations library. Also add
the Constant block from the Sources library to set the constant value of 10 for the position
of the obstacle.
Model the imperfect measurement that would be typical to a real sensor. Generate noise by
using the Band-Limited White Noise block from the Sources library. Set the Noise
power parameter to 0.001. Add the noise to the measurement by using an Add block from
the Math Operations library.
Model a digital sensor that fires every 0.1 seconds. In Simulink, sampling of a signal at a
given interval requires a sample and hold. Add the Zero-Order Hold block from
the Discrete library. After you add the block to the model, change the Sample
Time parameter to 0.1.
Add another Outport to connect to the sensor output. Keep the default value of the Port
number parameter.
19
2. Connect the new blocks. The output of the Integrator, Second-Order block is already connected
to another port. To create a branch in that signal, left-click the signal to highlight potential
ports for connection as shown in Fig 1.21, and click the appropriate port.
Annotate Signals
1. Double-click the signal and type the signal name a shown in Fig 1.22.
Fig 1.22 Name the signal line between the two bloacks
Fig 1.23 Signal names added to all the connections in the Simulink model
20
Compare Multiple Signals
Compare the actual distance signal with the measured distance signal.
1. Create and connect a Scope Viewer to the actual distance signal. Right-click the signal and
select Create & Connect Viewer > Simulink > Scope. The name of the signal appears in the
viewer title.
2. Add the measured distance signal to the same viewer. Right-click the signal and select Connect
to Viewer > Scope1 as shown in Fig 1.24. Make sure that you are connecting to the viewer
you created in the previous step.
3. Run the model. The Viewer shows the two signals, actual distance in yellow and measured
distance in blue as shown in Fig 1.25.
21
Fig 1.25 Scope showing measured distance in blue colour
4. Zoom into the graph to observe the effect of noise and sampling. Click the Zoom button .
Left-click and drag a window around the region you want to see more closely as shown in Fig
1.26.
22
You can repeatedly zoom in to observe the details.
Fig 1.27 Scope window magnifies the signal after clicking the zoom options
From the plot, note that the measurement can deviate from the actual value by as much as 0.3 m.
This information becomes useful when designing a safety feature, for example, a collision
warning.
23
1.5. TOOLBOX’s In MATLAB
The toolbox is a collection of functions built on the MATLAB® technical computing environment.
In every new release, there are enhancements in the existing toolboxes along with addition of new
toolboxes. The complete list of the MathWorks products and toolboxes in MATLAB 2020b can
be found out in the URL: https://www.mathworks.com/content/dam/mathworks/fact-sheet/2020b-
cwl-product-list.pdf. Deep Learning HDL, Lidar and UAV toolboxes are newly introduced.
Apart from that the existing toolboxes are listed below:
1. MATLAB
2. Simulink
3. 5G Toolbox
4. Aerospace Blockset
5. Aerospace Toolbox
6. Antenna Toolbox
7. Audio Toolbox
8. Automated Driving Toolbox
9. AUTOSAR Blockset
10. Bioinformatics Toolbox
11. Communications Toolbox
12. Computer Vision Toolbox
13. Control System Toolbox
14. Curve Fitting Toolbox
15. Data Acquisition Toolbox
16. Database Toolbox
17. Datafeed Toolbox
18. Deep Learning Toolbox
19. DO Qualification Kit (for DO-178)
20. DSP System Toolbox
21. Econometrics Toolbox
22. Embedded Coder
23. Filter Design HDL Coder
24. Financial Instruments Toolbox
25. Financial Toolbox
26. Fixed-Point Designer
24
27. Fuzzy Logic Toolbox
28. Global Optimization Toolbox
29. GPU Coder
30. HDL Coder
31. HDL Verifier
32. IEC Certification Kit (for ISO 26262 and IEC 61508)
33. Image Acquisition Toolbox
34. Image Processing Toolbox
35. Installation and Licensing
36. Instrument Control Toolbox
37. Licensing on the Cloud
38. LTE Toolbox
39. Mapping Toolbox
40. MathWorks Cloud Center
41. MATLAB Coder
42. MATLAB Compiler
43. MATLAB Compiler SDK
44. MATLAB Drive
45. MATLAB Grader
46. MATLAB Mobile for Android
47. MATLAB Mobile for iOS
48. MATLAB Parallel Server
49. MATLAB Production Server
50. MATLAB Report Generator
51. MATLAB Web App Server
52. Mixed-Signal Blockset
53. Model Predictive Control Toolbox
54. Model-Based Calibration Toolbox
55. Motor Control Blockset
56. Navigation Toolbox
57. OPC Toolbox
58. Optimization Toolbox
25
59. Parallel Computing Toolbox
60. Partial Differential Equation Toolbox
61. Phased Array System Toolbox
62. Polyspace Bug Finder
63. Polyspace Bug Finder Access
64. Polyspace Bug Finder Server
65. Polyspace Code Prover
66. Polyspace Code Prover Access
67. Polyspace Code Prover Server
68. Polyspace Products for Ada
69. Powertrain Blockset
70. Predictive Maintenance Toolbox
71. Reinforcement Learning Toolbox
72. RF Blockset
73. RF Toolbox
74. Risk Management Toolbox
75. RoadRunner
76. Robotics System Toolbox
77. Robust Control Toolbox
78. ROS Toolbox
79. Sensor Fusion and Tracking Toolbox
80. SerDes Toolbox
81. Signal Processing Toolbox
82. SimBiology
83. SimEvents
84. Simscape
85. Simscape Driveline
86. Simscape Electrical
87. Simscape Fluids
88. Simscape Multibody
89. Simscape Multibody Link
90. Simulink 3D Animation
26
91. Simulink Check
92. Simulink Code Inspector
93. Simulink Coder
94. Simulink Compiler
95. Simulink Control Design
96. Simulink Coverage
97. Simulink Design Optimization
98. Simulink Design Verifier
99. Simulink Desktop Real-Time
100. Simulink PLC Coder
101. Simulink Real-Time
102. Simulink Report Generator
103. Simulink Requirements
104. Simulink Test
105. SoC Blockset
106. Spreadsheet Link
107. Stateflow
108. Statistics and Machine Learning Toolbox
109. Symbolic Math Toolbox
110. System Composer
111. System Identification Toolbox
112. Text Analytics Toolbox
113. ThingSpeak
114. Trading Toolbox
115. Vehicle Dynamics Blockset
116. Vehicle Network Toolbox
117. Vision HDL Toolbox
118. Wavelet Toolbox
119. Wireless HDL Toolbox
120. WLAN Toolbox
27
LEARNING OUTCOMES
The students are able to understand the basic fundamentals in engineering mathematics
through the software toolbox.
The students are able to simulate the basic concepts of mathematics, science and
engineering
VIVA QUESTIONS
EXERCISES
Develop a m script file to identify the output of the below function and analyze the
function by varying the ‘x’ component
Construct a Simulink file to find the greatest among the three numbers.
Develop a Simulink model to identify the peak of the sine wave signal.
APPLICATIONS
MATLAB used in automobile industry for Vehicle dynamics, Track simulation and
Vehicle testing
MATLAB Simulink used in the Embedded Industry for standard code generation
28
MATLAB Simulink used biomedical industry to predict and analyze the chemical
reactions
MATLAB Control System module used in the process and production industry for
Control and Automation
MATLAB Image processing module in the Machine Vision system for image based
processing
CONCLUSION
The MATLAB components are studied in the command windows and scripts.
The Simulink modeling basics are practised by creating a model.
The MATLAB toolboxes are explored.
29
2. MATHEMATICAL OPERATIONS USING ARRAYS AND MATRICES
AIM
To use the concept of Arrays and Matrices by solving basic mathematical problems
DESCRIPTION
In this experiment, the declaration and manipulation of array and matrices are
demonstrated. The exercises provide the overview on Array and Matrix creations, Matrix and
Array operations, Concatenations, Array and Matrix expansions.
PRACTICE EXERCISES
All MATLAB variables are multidimensional arrays, no matter what type of data.
A matrix is a two-dimensional array often used for linear algebra.
2.1. Array Creation
To create an array with four elements in a single row, separate the elements with either a
comma (,) or a space.
>> a = [1 2 3 4]
a = 1×4
1 2 3 4
Another way to create a matrix is to use a function, such as ones, zeros, or rand.
Create a 5-by-1 column vector of zeros.
>> z = zeros(5,1)
z = 5×1
0
0
0
0
0
30
2.2. Matrix and Array Operations
MATLAB allows you to process all of the values in a matrix using a single arithmetic
operator or function.
>> a + 10
ans = 3×3
11 12 13
14 15 16
17 18 20
>> sin(a)
ans = 3×3
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
Perform standard matrix multiplication, which computes the inner products between rows
and columns, using the * operator.
Confirm that a matrix times its inverse returns the identity matrix:
>> p = a*inv(a)
p = 3×3
1.0000 0 0
0.0000 1.0000 0
0.0000 -0.0000 1.0000
Notice that p is not a matrix of integer values. MATLAB stores numbers as floating-point
values, and arithmetic operations are sensitive to small differences between the actual value and
its floating-point representation.
Display more decimal digits using the format command:
>> format long
>> p = a*inv(a)
p = 3×3
1.000000000000000 0 0
31
0.000000000000002 1.000000000000000 0
0.000000000000002 -0.000000000000004 1.000000000000000
format affects only the display of numbers, not the way MATLAB computes or saves them.
The matrix operators for multiplication, division, and power each have a corresponding
array operator that operates element-wise.
Raise each element of a to the third power:
>> a.^3
ans = 3×3
1 8 27
64 125 216
343 512 1000
Concatenation
Concatenation is the process of joining arrays to make larger ones. In fact, you made your
first array by concatenating its individual elements. The pair of square brackets [] is the
concatenation operator.
>> A = [a,a]
A = 3×6
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
Concatenating arrays next to one another using commas is called horizontal concatenation.
Each array must have the same number of rows. Similarly, when the arrays have the same number
of columns, you can concatenate vertically using semicolons.
>> A = [a; a]
A = 6×3
1 2 3
4 5 6
7 8 10
32
1 2 3
4 5 6
7 8 10
Complex Numbers
Complex numbers have both real and imaginary parts, where the imaginary unit is the
square root of -1.
>> sqrt(-1)
ans = 0.0000 + 1.0000i
Array Indexing
Every variable in MATLAB® is an array that can hold many numbers. When you want to access
selected elements of an array, use indexing.
Consider the 4-by-4 magic square A:
>> A = magic(4)
A = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Less common, but sometimes useful, is to use a single subscript that traverses down each
column in order:
>> A(8)
ans = 14
Using a single subscript to refer to a particular element in an array is called linear indexing.
Refer to elements outside an array on the right side of an assignment statement, MATLAB
throws an error.
33
>> test = A(4,5)
Index exceeds matrix dimensions.
On the left side of an assignment statement, specify elements outside the current
dimensions. The size of the array increases to accommodate the newcomers.
>> A(4,5) = 17
A = 4×5
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
Refer to multiple elements of an array, use the colon operator, which allows to specify a
range of the form start:end.
List the elements in the first three rows and the second column of A:
>> A(1:3,2)
ans = 3×1
2
11
7
The colon alone, without start or end values, specifies all of the elements in that dimension.
Select all the columns in the third row of A:
>> A(3,:)
ans = 1×5
9 7 6 12 0
The colon operator allows to create an equally spaced vector of values using the more
general form start:step:end.
>> B = 0:10:100
B = 1×11
0 10 20 30 40 50 60 70 80 90 100
34
Name Size Bytes Class Attributes
A 1x1 8 double
A = 1×4
12 62 93 -8
>> sz = size(A)
sz = 1×2
1 4
Create a matrix with the same numbers, but arrange them in two rows. This matrix has two
rows and two columns.
>> A = [12 62; 93 -8]
A = 2×2
12 62
93 -8
sz = size(A)
sz = 1×2
2 2
2.4 Specialized Matrix Functions
MATLAB has many functions that help create matrices with certain values or a particular
structure.
The zeros and ones functions create matrices of all zeros or all ones. The first and second
arguments of these functions are the number of rows and number of columns of the matrix,
respectively.
A = zeros(3,2)
A = 3×2
0 0
0 0
0 0
35
B = ones(2,4)
B = 2×4
1 1 1 1
1 1 1 1
The diag function places the input elements on the diagonal of a matrix.
Create a row vector A containing four elements. Then, create a 4-by-4 matrix whose
diagonal elements are the elements of A.
>> A = [12 62 93 -8];
>> B = diag(A)
B = 4×4
12 0 0 0
0 62 0 0
0 0 93 0
0 0 0 -8
C = 1×8
1 1 1 1 0 0 0 0
D = 2×4
1 1 1 1
0 0 0 0
To concatenate two matrices, they must have compatible sizes. In other words, when
concatenating matrices horizontally, they must have the same number of rows. When
concatenating them vertically, they must have the same number of columns.
Horizontally concatenate two matrices that both have two rows.
>> A = ones(2,3)
A = 2×3
1 1 1
1 1 1
36
>> B = zeros(2,2)
B = 2×2
0 0
0 0
>> C = [A B]
C = 2×5
1 1 1 0 0
1 1 1 0 0
D = 2×5
1 1 1 0 0
1 1 1 0 0
Use the colon operator to create a sequence of numbers within any range, incremented by
one.
>> A = -2.5:2.5
A = 1×6
-2.5000 -1.5000 -0.5000 0.5000 1.5000 2.5000
Change the value of the sequence increment, specify the increment value in between the
starting and ending range values, separated by colons.
>> A = 0:2:10
A = 1×6
0 2 4 6 8 10
37
Increment by non-integer values
>> A = 1:0.2:2.1
A = 1×6
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
>> A(3,4) = 1
A = 3×4
10 20 30 0
60 70 80 0
0 0 0 1
Expand the size by inserting a new matrix outside of the existing index ranges.
>> A(4:5,5:6) = [2 3; 4 5]
A = 5×6
10 20 30 0 0 0
60 70 80 0 0 0
0 0 0 1 0 0
0 0 0 0 2 3
0 0 0 0 4 5
LEARNING OUTCOMES
The students are able to understand the basic matrix and array manipulation through the
software toolbox.
The students are able to analyze complex engineering problems using first principles of
mathematics and engineering sciences
VIVA QUESTIONS
1. Infer whether functions available for Matrix can be applied to array.
2. Identify whether the elements of Matrix be generated randomly
3. What are the operators supported by MATLAB?
4. Explain the process to pre-allocate a non-double Matrix
5. How do you convert an array into a square matrix?
38
6. List out the five array functions used in the MATLAB
7. What is the purpose of using magic square in multidimensional array?
8. How to trim the declared array using MATLAB function?
9. List out the functions available in the MATLAB to generate random elements in the Array/
Matrix.
10. How will identify that the given input is in matrix format?
EXERCISES
𝜋
Generate the vector z, where 𝑧 = 𝜔
2
o Extract the fourth element of the vector z
o Extract the first three elements of the vector z
o Find the length of the vector z
o Find the total sum of the values of the elements of the vector z
o Find the minimum and maximum values of the elements of the vector z.
3 0 −2
Generate the following rectangular matrix in MATLAB 𝐴 =
1 3 5
o Extract the element in the second row and second column of the matrix A
o Generate a new matrix B of the same size by multiplying the matrix A by the
3𝜋
number
2
o Extract the element in the first row and third column of the matrix B.
o Extract the sub-matrix of the elements in common between the first and second
rows and the second and third columns of the matrix B.
o Determine the largest of the number of rows and columns of the matrix B using the
MATLAB command length
APPLICATIONS
Matrix used in all Digital Image Processing techniques
Arrays used in .NET applications
Matrix and Arrays used in Digital Control System techniques
Arrays are used in stress analysis for different materials
CONCLUSION
The creation and storing of Matrices and Arrays are practiced.
The manipulation of Matrices and Arrays are practiced.
39
3. CREATE AND MANIPULATE THE VARIABLES FOR TEXT AND
NUMERIC DATA TYPES
AIM
To create, represent, use and manipulate the text in terms of strings and characters along
with the numeric data types.
DESCRIPTIONS
In this experiment, the creation and manipulation of text and numeric data types are
demonstrated. The exercises provide the overview on creating string and numeric data types, string
manipulation and conversion of numeric data types.
PRACTICE EXERCISES
When you are working with text, enclose sequences of characters in double quotes. You can assign
text to a variable.
>> whos t
Name Size Bytes Class Attributes
t 1x1 174 string
40
Note:
Creating string arrays with double quotes was introduced in R2017a. If you are using an earlier
release, create character arrays. For details, see Data in Character Arrays.
Create text includes double quotes. Add text to the end of a string. Concatenate text using
the append function.
The string function can convert different types of inputs, such as numeric, datetime, duration,
and categorical values.
The multiple pieces of text in a string array can be stored. Each element of the array can
contain a string having a different number of characters, without padding.
N = 2×3
7 6 6
6 8 3
Functions that accept character arrays (and cell arrays of character vectors) as inputs also
accept string arrays.
41
Represent Text with Character Vectors
Store a 1-by-n sequence of characters as a character vector, using the char data type,
enclose it in single quotes.
The text 'Hello, world' is 12 characters long, and chr stores it as a 1-by-12 character
vector.
ans =
'AGA'
Concatenate character vector with square brackets, just as you concatenate other types of
arrays.
Concatenate text using append. The append function is recommended because it treats
string arrays, character vectors, and cell arrays of character vectors consistently. MATLAB
functions that accept string arrays as inputs also accept character vectors and cell arrays of
character vectors
Add a space between the input strings, specify a space character as another input argument.
43
Create an array of file extension names, with a different extension for each element
of names.
Append the same extension to each name, use a character vector or a string scalar.
Implicit Expansion
44
Split String and Find Unique Words
Find the unique words in a string, split it on space characters and call the unique function.
Split str on space characters using the split function. split discards the space characters and
returns the result as a string array.
>> str = split(str)
str = 9x1 string
"a"
"horse"
"a"
"horse"
"my"
"kingdom"
"for"
"a"
"horse"
45
>> str = string(A)
str =
"Four score and seven years ago"
str contains the same characters as A. But while A is a character vector, str is a string scalar.
>> c = size(A)
c = 1×2
1 30
>> s = size(str)
s = 1×2
1 1
When the input argument is a string array, the double function treats each element as the
representation of a floating-point value. However, when the input is a character
array, double instead converts each character to a number representing its Unicode value.
Use the str2double function. str2double is suitable when the input argument might be
a string array, character vector, or cell array of character vectors.
>> Y = str2double(str)
Y = 1×3
256.0000 3.1416 0.0089
>> C = '2.7183';
>> Z = str2double(C)
Z = 2.7183
D = 1x3 duration
23.134 hr 24.134 hr 25.134 hr
str = 1x3 string
"23.134 hr" "24.134 hr" "25.134 hr"
str is a string array with one duration value per element. str is the same size as D.
47
Find the lengths of strings using strlength
Create a string using double quotes. The result is a 1-by-1 string array, or string scalar.
48
Character vectors are not strings, so isstring returns 0.
Test a string array
Numeric Values
Convert numeric value to strings
>> d=datetime('now');
>> string(d)
ans = "20-Feb-2020 09:27:55"
49
Convert duration array to character array
>> e=hours(23:25)+minutes(8)+seconds(1.2345)
>> f=char(e)
e = 1×3 duration array
23.134 hr 24.134 hr 25.134 hr
f = 3×9 char array
'23.134 hr'
'24.134 hr'
'25.134 hr'
LEARNING OUTOCMES
The students are able to understand the text and numeric data type manipulation through
the software toolbox.
The students are able to apply in an engineering specialization to the solution of complex
engineering problems.
VIVA QUESTIONS
1. List out the functions in MATLAB to manipulate the string / character array.
2. How to add a character after the 4th element of a string?
3. Point out the function to determine the length of the string
4. Compare the results of the functions strlength() and length() when applied to a string.
5. Why Does Appending Strings Using Square Brackets Return Multiple Strings?
6. List out the functions available in the MATLAB for numeric manipualtions
7. Identify whether the numeric value can be stored as character in the array.
8. Point out the function to convert the numeric data into string.
9. How will you find the indices of the maximum (or minimum) value of character array of
numeric data?
10. List out the data types available in MATLAB to represent numeric data.
EXCERCISES
From the given string array “str_array”, combine the first three colours in one string
variable and remaining in another string variable. str_array = {'red','blue','green', 'yellow',
'orange'};
A palindrome is a word or phrase that is spelled the same forwards or backwards (like "a",
"bb", and "ma'am").
o Write a sub-function named Is_palindrome() with one string input argument and
one logical output argument. The function should return true if the input argument
is a palindrome (ignoring case) and false otherwise.
o Add code to palindrome code that gets a string from the user, calls your
Is_palindrome() function and then reports whether or not the user-entered string is
a palindrome (ignoring case).
Calculate both the area and perimeter of a rectangle of sides 5 and 7 & a circle of radius
6.45
Let x = 5.5 and y = -2.6. Calculate the value of the variable z = 2x-3y.
o Calculate the value of the variable w = 3y – z + x/y
50
Let r = 6.3 and s = 5.8. Calculate the value of the variable final defined by final = r + s -
r*s.
o Calculate the value of the variable this_is_the_result defined by this_is_the_result
= r^2 – s^2
CONCLUSION
Thus the strings and characters along with the numeric data types are created, represented,
and its manipulation are practiced.
51
4. IMPORT AND EXPORT DATA AS TEXT FILES, SPREADSHEETS,
OTHER FILE
FORMATS AND WEB ACCESS
AIM:
To import data from a text file with column headers and numeric data using the Import
Tool
DESCRIPTION
In this experiment, the data import from the spread sheet files and from text files
are demonstrated. The exercises provide the overview on writing data into the spread sheet files
and to access the data from spreadsheet files and text files.
PRACTICE EXERCISE
The most basic form which will save all of the data present in a session. Here we save all
of the data in a file called “sample.mat.”
>> u = [1 2 3];
>> v = [4 6 8];
>> whos
Name Size Bytes Class
The data can be read back in to a Matlab session with the load command.
>> clear
>> whos
>> load stuff.mat
>> whos
Name Size Bytes Class
Write and read the data from the Excel spread sheet.
52
>> xlswrite(‘abc.xlsx’,[1, 2, 3, 4, 5])
>> xlsread (‘abc.xlsx’)
ans =
1 2 3 4 5
Input the two variable data into the excel sheet
>> data1 = [ 21 22 23; 24 25 26; 27 28 29 ; 30 31 32]
>> data2 = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
>> xlswrite(‘ file2.xlsx ‘ , [data1 ; data2])
>> xlsread(‘file2.xlsx’)
ans =
21 22 23
24 25 26
27 28 29
30 31 32
1 2 3
4 5 6
7 8 9
10 11 12
Import Data ti the MATLAB using command importdata
>> filename = ‘matlab.jpg’;
>> A = importdata(filename);
>> image(A);
53
Note that in the above example, the image should be placed in the current directory
Create a notepad file in the name ‘weeklydata.txt’ with the following content
SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay
95.01 76.21 61.54 40.57 55.79 70.28 81.53
73.11 45.65 79.19 93.55 75.29 69.87 74.68
60.68 41.85 92.18 91.69 81.32 90.38 74.51
48.60 82.14 73.82 41.03 0.99 67.22 93.18
89.13 44.47 57.63 89.36 13.89 19.88 46.60
SunDay
95.0100
73.1100
60.6800
48.6000
89.1300
54
>> end
SunDay
95.0100
73.1100
60.6800
48.6000
89.1300
MonDay
76.2100
45.6500
41.8500
82.1400
44.4700
LEARNING OUTCOMES
The student will be able to access the data stored in the files for the manipulation and
analysis purpose using the software
The students are able to apply in an engineering specialization to the solution of complex
engineering problems.
VIVA QUESTIONS
1. How to access the variable in the workspace that are stored in the structure format?
2. Point out the function used store the all the variable in the workspace into one file.
3. Infer the function to store the data from the workspace into a .mat file.
4. Identify whether the data from xlsread() function is in matrix format.
5. Check whether the images are stored in the form of matrix.
6. Identify whether the MATLAB can append a data in a excel file which is already open.
7. Point out the method to specify the path of the excel file in the xlsread() function.
8. Mention the function to upload the data to.txt file.
9. Point out the function to import the .mat file data in command prompt.
10. Mention the functions to store the data from workspace.
55
EXCERCISES
Create an excel spread sheet in the name ‘Templog’ using xlswrite for the following data
and import the first 5 rows of data from the same file using xlsread.
Load an image using importdata command and using the same command extract first 5
columns of image data
Save the Templog data in the .dat formate and extract the time coloumn using the
importdata command
APPLICATIONS
Data used in Data Science technology for data processing to understand the system
dynamics
System data are stored and then processed to develop Artificial Intelligence model for the
applications like Image Processing, Decision making, Data Prediction etc.,
Data are used in the graphs for better understand on the data dynamics
Data are created by storing the sensors values with respective time and then data science
methods are applied to predict the sensor behavior
CONCLUSION
The data are created and same accessed using the software commands to view the data.
56
5. CREATE VARIABLES WITHIN /IMPORT INTO WORKSPACE OF
MATLAB FROM DATA FILES OR OTHER PROGRAMS
AIM
To create a data file and import the data and plot the graph for the data.
DESCRIPTIONS
In this experiments, access of data from workspace or storing a data in the workspace are
demonstrated. The practical exercise overview on access of excel data using xlsread command
and manipulate the data using basic MATLAB functions.
PRACTICE EXERCISE
>> % create variables within/import into workspace of matlab from data files
>> % The command xlsread is used to read data from excel sheet
>> data=xlsread('C:\Users\geethasree\Documents\data.xlsx');
>> % Access the entire rows and first column of the excel sheet
>> x=data(:,1);
>> % Access the entire rows and second column of the excel sheet
>> y=data(:,2);
>> plot(x,y);
>> title('plot');
57
>> stackedplot(x,y); title('stackedplot');
>> semilogx(x,y);
>> title('semilog');
59
Fig 6.9 Data plotted using scatter function
>> plotmatrix(x,y);
>> title('plotmatrix');
comet(x,y);
title('comet');
60
Fig 6.12 Data plotted using bar function
>> barh(x,y);
>> title('horizontalbar');
>> pareto(y,x);
>> title('paretochart');
61
Fig 6.15 Data plotted using stem function
LEARNING OUTCOMES
The student will be able to store and access the data in the different format for further
analysis.
The student will be able to select, and apply appropriate data storing / retrieving techniques.
VIVA QUESTIONS
1. Point out the function to import data into the workspace variable.
2. Identify the save function format to export the data in 7.3 version MATLAB .mat format.
3. How to create multiple workspace in MATLAB?
4. List of the parameters in the save function to save the data from workspace.
5. Identify the functions similar to “save” function to save data from workspace.
6. Mention the parameters available in load to import the data to workspace.
7. How to shuffle the data imported in the workspace?
8. How will you display the data of a variable in the command prompt itself?
9. Mention the parameters in the “who” function to list the variables in the workspace
10. Mention the different format to save the data from workspace variable.
EXERCISE
Create a data with Time and its respective room temperature in a excel sheet. Then access
the data in the excel sheet using the xlsread() command and plot the data
Create a data with Force in Newton and its respective material expansion in mm in a excel
sheet. Using the xlsread() and for loop command, calculate the stress value for each applied
force on the material
APPLICATIONS
The data accessing techniques are used in Machine Learning and Deep Learning concepts.
The data accessing techniques are used in Signal processing and embedded applications.
The data accessing techniques are used in data science applications.
CONCLUSION
The data from the file is imported and the data are used to plot various types of plots.
62
6. BASIC PROGRAMS IN SCRIPTS CONTAINING SEQUENCE OF
COMMANDS AND FUNCTIONS
AIM:
To practice the script file for execute set of multiple sequential lines of MATLAB
commands and function calls.
DESCRIPTION
In this experiment, the MATLAB m scripts programs are demonstrated. This experiment
provide overview on creating and execution of the m script program. M script programs are used
to execute the collection of MATLAB commands for single purpose and this also can be as
function script. In recent, MATLAB Live script is used to provide the graphical output in the script
file itself.
PRACTICE EXCERISE:
To create scripts files, you need to use a text editor. You can open the MATLAB editor in two
ways
63
Create script file to solves the quadratic equation x2 -7x +12 = 0
eq = 'x^2 -7*x + 12 = 0';
s = solve(eq);
disp('The first root is: '), disp(s(1));
disp('The second root is: '), disp(s(2));
Command Prompt
>>
The first root is:
3
The second root is:
4
mysphere
You can also run scripts from the Editor using the Run button, and result shown in figure
window as shown in Fig 6.2
Command Prompt:
>> mymax(34, 78, 89, 23, 11)
ans = 89
Live Script
Instead of writing code and comments in plain text, you can use formatting options in live
scripts to enhance your code. Live scripts allow you to view and interact with both code and output
and can include formatted text, equations, and images.
To create a live script in the Live Editor, go to the Home tab and click New Live
Script .
You also can use the edit function in the Command Window. For example, type edit
penny.mlx
65
Rewrite the text to replace the comments at the end of code lines. To apply a monospace
font to function names in the text, select . To add an equation, select Equation on
the Insert tab.
To create a new live script using the edit command, include the .mlx extension with the file name:
66
Fig 6.4 Live script file to identify the mean of random data
Run Code
To run the code, click the vertical striped bar to the left of the code.
Fig 6.5 Live script file to plot the mean of random data
LEARNING OUTCOMES
The student are able to apply m script, function script and live script to demonstrate and
solve the engineering concepts
The student will able to provide solutions for complex engineering problems or processes
that meet the specified needs
VIVA QUESTIONS
1. Infer the method to call the M script form a Simulink file.
2. Point the MATLAB syntax format to convert the script file into function file.
3. List the commands to clear the previous program’s variable before the current program
being executed.
4. How to call the function script from the command prompt?
5. Mention the graphic functions handled by the live script.
6. Identify whether the function script can accept the matrix and vector as passing parameters.
7. How to set/clear break points in the M script files to debug the program?
8. Specify the commands to get the input and print the output from the M file.
9. How to create a new M file from command prompt?
10. How to run the M File from command prompt?
67
EXERCISES
Write a function file that converts temperature in degrees Fahrenheit (◦F) to degrees
Centigrade (◦C). Use input and fprintf commands to display a mix of text and numbers.
Recall the conversion formulation, C = 5/9 ∗ (F − 32).
Write a user-defined MATLAB function, with two input and two output arguments that
determines the height in centimeters (cm) and mass in kilograms (kg)of a person from his
height in inches (in.) and weight in pounds (lb).
o Determine in SI units the height and mass of a 5 ft.15 in. person who weight 180lb.
o Determine your own height and weight in SI units.
Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 ∗ cos(x), in
the interval 0 ≤ x ≤ 2π using Live Script
APPLICATIONS
M scripts are used to solve complex mathematical problems
It is used to simulate the system’s behavior which are not user customizable in the
MATLAB Simulink
It is used in the Data analysis where the data are stored in the excel sheet or .dat format
It is used in Control system applications to analyze the sytem and controller behavior
It is used to program the Arduino, Raspberry pi development board for any embedded
applications
CONCLUSION:
Thus the development of script, function call and live script are created. The input
argument passing and output of the m script files are done in the command window.
68
7. BASIC PROGRAMS USING LOOPS AND CONDITIONAL
STATEMENTS, SUCH AS IF, FOR, AND WHILE
AIM
To practice the basic programs using loops and conditional statements using MATLAB.
DESCRIPTION
In this experiment the program flow controls like for loop, while loop, if conditions are
demonstrated. The exercise provide the overview on initialization of the loop, loop condition and
loop termination.
PRACTICE EXERCISE
All the program created using m scripts and the results are viewed in the command window.
IF LOOP
>> if E<30
69
>> disp('small')
>> elseif E<80
>> disp('medium')
>> else
>> disp('large')
>> end
large
FOR LOOP
>> % Basic programs using for
>> for G=1:5
>> fprintf('value of G: %d\n',G)
>> end
value of G: 1
value of G: 2
value of G: 3
value of G: 4
value of G: 5
70
newch = 'ba'
newch = 'bal'
newch = 'balt'
newch = 'balta'
newch = 'baltam'
>> % Fibonaaci using For Loop
>> function f = fibonacci(N)
>> f=zeros(N,1);
>> f(1)=0;
>> f(2)=1;
>> for k=3:N
>> f(k)=f(k-1)+f(k-2);
>> end
>> end
At command window
>> fibonacci(3)
0
1
1
2
3
5
>> % Display using For Loop
>> for a = 1.0: -0.1: 0.0
>> disp(a)
>> end
1
0.9000
0.8000
0.7000
0.6000
0.5000
0.4000
0.3000
0.2000
0.1000
0
>> % Display using For Loop
>> for a = [24,18,17,23,28]
>> disp(a)
>> end
24
18
71
17
23
28
WHILE LOOP
% while loop for printing prime numbers
>> clc
>>clear all
>> n=input('num : ');
>> while i<=sqrt(n)
>> if n==0| n==1
>> disp('not a prime number')
>> else
>> disp(n)
>> disp('prime number')
>> break
>> end
>> i=i+1;
>> end
At the command window
>> 3
prime number
>> % Basic programs using while
>> F=5
>> while(F<10)
>> fprintf('\nvalue of F: %d\n',F)
>> F=F+1
>> end
F=5
value of F: 5
F=6
value of F: 6
F=7
value of F: 7
F=8
value of F: 8
F=9
value of F: 9
F = 10
>> % a value increment using while loop
>> a = 10;
>> % while loop execution
>> while( a < 20 )
>> fprintf('value of a: %d\n', a);
72
>> a = a + 1;
>> end
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
NESTED LOOPS
% Use a nested for loop to display all the prime numbers from 1 to 100
for i=2:100
for j=2:100
if(~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
% Example for break statement
a = 10;
% while loop execution
while (a < 20 )
fprintf('value of a: %d\n', a);
a = a+1;
if(a >15)
% terminate the loop using break statement
break;
end
end
a = 10;
%while loop execution
while a < 20
if a == 15
% skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end
73
LEARNING OUTCOMES
The student will able change the program flow using loop statement and if conditions based
the application requirement
The students are able to apply in an engineering specialization to the solution of complex
engineering problems.
VIVA QUESTIONS
1. Mention the functions to get the input value from the user and to print the statement in the
command window.
2. What is the default increment value in a for-loop?
3. Point out the function to pause the loop / if statement program in a specific line.
4. Identify whether the value of the variable can be accessed when the loop is running.
5. Point out the loop method to run the process for infinite times.
6. Mention the command to stop execution when the loop executes for infinite times.
7. How many “end” terminals required for a nested loops in an applications?
8. Infer the method to implement “do while” loop in the MATLAB.
9. Mention the method to modify the incremental order in for loop.
10. Infer the effects when there is no statements inside a loop.
EXCERCISES
Calculate the voltage stored in the capacitance for 10 different capacitance value using for
loop, for the same time period
Create a program in m script to display the such a pattern for n number of rows using a
number which will start with the number 1 and the first and a last number of each row will
be 1.
Create a program in m script to find the number and sum of all integer between 100 and
200 which are divisible by 9
Develop m script program to store the value of sensor continuously and terminate the loop
when the count reaches 40,000.
APPLICATIONS
Loops are used in stress and strain analysis of materials using MATLAB M scripts
Loops used in the simulation of mathematical model of electronics and electrical circuits
using m script
Condition statement and Loops are used in the AI techniques to repeat the training process
( epochs) and to set the weights for the input / output
Loops and control statements are used in MATLAB Embedded programming
CONCLUSION
The loops and if statements are created using m script and their effects on the program flow
displayed in the command window
74
8. SOLVING MATHEMATICAL FUNCTIONS USING COMPUTATIONAL
SOFTWARE
AIM
To solve mathematical functions using the MATLAB commands and M script files.
DESCRIPTION
In this experiment, the m scripts are demonstrated to solve the mathematical functions. In
this experiment, m script file is created and the plot functions are used to analyze the results
obtained from the m scripts.
PRACTICE EXCERISE
%Solve system of linear equations
%using linsolve
%Declare the system of equations.
syms x y z
eqn1 = 2*x + y + z == 2;
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -10;
B=
%using solve
sol = solve([eqn1, eqn2, eqn3], [x, y, z]);
xSol = sol.x
>> xSol = 3
75
>> ySol = sol.y
ySol = 1
>> zSol = sol.z
zSol = -5
Solve Polynomial and Return Real Solutions
>> syms x
>> eqn = x^5 == 3125;
>> S = solve(eqn,x)
5
- (2^(1/2)*(5 - 5^(1/2))^(1/2)*5i)/4 - (5*5^(1/2))/4 - 5/4
(2^(1/2)*(5 - 5^(1/2))^(1/2)*5i)/4 - (5*5^(1/2))/4 - 5/4
(5*5^(1/2))/4 - (2^(1/2)*(5^(1/2) + 5)^(1/2)*5i)/4 - 5/4
(5*5^(1/2))/4 + (2^(1/2)*(5^(1/2) + 5)^(1/2)*5i)/4 - 5/4
%Solve differential solution
% Initial Value theorem
tspan = [0 20];
y0 = [2; 0];
Mu = 1;
ode = @(t,y) vanderpoldemo(t,y,Mu);
[t,y] = ode45(ode, tspan, y0);
% Plot solution
plot(t,y(:,1))
xlabel('t')
ylabel('solution y')
title('van der Pol Equation, \mu = 1')
76
Solve Polynomial Equation using polyval
The value of the polynomial q above at x = –1
>> polyval(q,-1)
ans =
7
Finding the roots of a polynomial is as easy as entering the following command.
>> roots(q)
ans =
0
0.0712 + 2.6486i
0.0712 - 2.6486i
-0.1424
% Interpolation
x = rand(1,500)/100;
y = 2.*(rand(1,500)-0.5).*90;
z = (x.*1e2).^2;
X = linspace(min(x),max(x),25);
Y = linspace(min(y),max(y),25);
[xq, yq] = meshgrid(X,Y);
zq = griddata(x,y,z,xq,yq);
plot3(x,y,z,'mo')
hold on
mesh(xq,yq,zq)
xlabel('x')
ylabel('y')
hold off
77
% Normalize Sample Points
x = normalize(x);
y = normalize(y);
% Regenerate Grid
X = linspace(min(x),max(x),25);
Y = linspace(min(y),max(y),25);
[xq, yq] = meshgrid(X,Y);
% Interpolate and Plot
zq = griddata(x,y,z,xq,yq);
plot3(x,y,z,'mo')
hold on
mesh(xq,yq,zq)
LEARNING OUTCOMES
The student will able to apply mathematical software tools to solve the complex
engineering problems
The student will able to analyze complex engineering problems reaching substantiated
conclusions using first principles of mathematics and engineering sciences
VIVA QUESTIONS
1. How do the ODE solvers differ from quad or quadl?
2. Mention the parameters available in the solve() function.
3. Infer the purpose of the function “sym” to solve the mathematical equations.
4. Identify whether the solve() function can accept the matrix as input parameter to solve the
equation.
5. Compare the function solve() and normalization() in MATLAB.
6. How to change the ODE solver in the MATLAB Simulink?
78
7. Mention the functions used to solve the partial differential equations.
8. List the functions available to solve the ordinary differential equations.
9. Identify whether the output of a function solver and the results obtained from the graph
are same
10. List out the specific graph functions used solve the mathematical problems.
EXERCISE
Write a function m-file called polyadd.m that adds two polynomials (of not necessarily the
same degree). The input should be the two vectors of coefficients and the output should be
a new vector of coefficients representing their sum.
Find the maxima and minima (if any) of the polynomial function f(x) = x 3 – x 2 –3x. Plot
the function and the maxima and minima (if any) using a ‘o’ for each minimum and a ‘*’
for each maximum.
Write a script file to set a value for d, a distance in km, and calculate how long it takes to
drive that distance at 80 kph.
APPLICATIONS
MATLAB math function are used to solve the polynomial equations in the mathematical
modelling of system, signal, electrical system etc..
MATLAB math used to solve the algebraic equation for the curve fitting applications
It is used to simulate the mathematical model of any physical system
MATLAB math function used in the Control System and Signal processing application for
simulation
CONCLUSION
The m scripts are created to solve the mathematical functions and the results are verified
using the plot functions
79
9. SOLVING MATRICES AND VECTORS PROBLEMS USING
COMPUTATIONAL SOFTWARE
AIM
To solve the given Matrices and Vector based problems using MATLAB basic functions.
DESCRIPTION
In this experiment, the matrices and vectors operations shown in using MATLAB functions
to solve the simultaneous equation. The practical exercise provide overview of creating a vector
/ matrices from the simultaneous equations, to solve the equations.
EXERCISE
[ 1, -1, 2]
[ 1, 2, 3]
[ 2, 1, 1]
b=
-3
4
-3
vars =
[ x, y, z]
80
Solving simultaneous equation by Matrix Cramer’s rule. The equations are
x-y+2z=-3;
x+2y+3z =4;
2x+y+z=-3;
>> clc
>> clear ll
>> close all
>> %variables used
>> % A is the array of x,y coefficient
>> % b is the array of constants
>> % B is an array of determinants
>> [i,j]=size(A);
81
Solving surface equation to identify the intersection point using Matrix
x+2y-z=1
x+y-z=2
x-y+z=0
>> z1=@(x,y) x+2*y-1
z1 =
function_handle with value:
@(x,y)x+2*y-1
z2 =
function_handle with value:
@(x,y)x+y-2
82
>> z3=@(x,y) y-x
z3 =
function_handle with value:
@(x,y)y-x
Solve the equation using Matrix to find the intersection point of the three planes
>> syms x y z
>> eqns = [x+2*y-z == 1,
>> x+y-z == 2,
83
>> x-y+z == 0];
>> [A,b] = equationsToMatrix(eqns)
>> vars = symvar(eqns)
A=
[ 1, 2, -1]
[ 1, 1, -1]
[ 1, -1, 1]
b=
1
2
0
vars =
[ x, y, z]
>> inv(A)*b
ans =
1
-1
-2
Solve Multivariate Equations and Assign Outputs to Structure
>> syms u v
>> eqns = [2*u + v == 0, u - v == 1];
>> S = solve(eqns,[u v])
The student will be able to solve the engineering problems using MATLAB matrix and
vector functions.
The student will be able to apply matrices and vectors, in an engineering specialization
to the solution of complex engineering problems
84
VIVA QUESTIONS
1. List out the functions used to generate random elements in the matrix.
2. Identify whether the manipulation functions are common for both matrix and vector.
3. How will you convert a matrix to vector and vice versa in the MATLAB?
4. Mention the specific functions used for matrix manipulation.
5. Point out the function to identify the empty matrix and its return value.
6. List the special functions used for the vector manipulation.
7. How will you convert the simultaneous equation into matrix?
8. Infer the function to identify the size of the matrix and vector.
9. When will you apply the magic() function in the matrix?
10. Compare rand() and magic() function applied in the matrix/vector creation.
EXERCISE
APPLICATIONS
Matrices and vectors functions are used to solve the algebraic equations
To store the results of Machine Learning in the vector format
CONCLUSION
Thus the App was created for temperature unit conversion using MATLAB App
designer.
85
10. CREATE 2D,3D PLOTS AND DISPLAY IT IN GRAPHICAL
WINDOW USING COMPUTATIONAL SOFTWARE
AIM
To create 2-D and 3-D plots to visualize data into pictorial view.
DESCRIPTION
In this experiment the plot functions to create a 2D and 3D graphs are demonstrated. The
exercise provide the overview on the 2D, 3D plot function and its associative parameters like
colour, variable, line type.
PRACTICE EXCERISE:
% Plot the same variables with specified line style, color, and marker
86
(A marker is a symbol that appears at each plotted data point, such as a +, o, or *).
Use 'help plot' to learn more about line specification.
% In this experiment, the 'r--' string is a red dashed-line specification.
figure
plot(x, y, 'r--')
title('Plot of the Sine Function (Red Dashed-line)')
Fig 10.2 Simple plot graph for sine wave with red dashed line
% To add plots to an existing figure, use hold.
figure
plot(x, y)
hold on
y2 = cos(x);
plot(x, y2, ':')
legend('sin', 'cos')
title('Plot of Sine and Cosine Functions')
%%
% Use 'hold off' to stop plotting on top of the existing figure.
hold off
Fig 10.3 Simple plot graph for sine and cos wave
87
%% Creating 3-D Scatter Plots
% Show how to create a 3-D scatter plot in MATLAB.
% Use the scatter3 function
% Load data on ozone levels.
load ozoneData Ozone Temperature WindSpeed SolarRadiation
% Calculate ozone levels.
z = (Ozone).^(1/3);
response = z;
% Make a color index for the ozone levels.
nc = 16;
offset = 1;
c = response - min(response);
c = round((nc-1-2*offset)*c/max(c)+1+offset);
% Create a 3-D scatter plot using the scatter3 function.
figure
scatter3(Temperature, WindSpeed, SolarRadiation, 30, c, 'filled')
view(-34, 14)
% Add title and axis labels.
title('Ozone Levels')
xlabel('Temperature')
ylabel('Wind Speed')
zlabel('Solar Radiation')
% Add a colorbar with tick labels.
% Use ellipsis '...' to continue a statement to the next line.
colorbar('Location', 'EastOutside', 'YTickLabel',...
{'2 ppm', '4 ppm', '6 ppm', '8 ppm', '10 ppm', '12 ppm', '14 ppm'})
LEARNING OUTCOMES
The student will be able to configure the plot function as required for the application
The student will be able to apply the plot function in mathematics, science, engineering
fundamentals, and an engineering specialization
88
VIVA QUESTIONS
1. List out the functions available to plot 2 dimensional graphs.
2. Mention the parameters available for the plot() function.
3. Identify the number of face format to differentiate the signals in the plot.
4. Identify the format to represent the colour to differentiate the signals in the plot.
5. Compare the functions in the plot() and scope in the Simulink.
6. List out the functions available to plot the 3 dimensional graphs.
7. Mention the plot functions used to plot the simultaneous equations.
8. Identify which plot functions required equal size of x vector and y vector.
9. Mention three different update methods in the plot() function.
10. Mention the methods to high light the legend and name of the x,y axis on the graph.
EXERCISE
Write down the function g(t) that has the shape of a sine wave that increases linearly in
𝜋𝑡 2
frequency from 0 Hz at t = 0 s to 5 Hz at t = 10 s. 𝑔(𝑡) = sin( )
2𝑠 2
o Plot the graph of this function using MATLAB’s plot command.
o Add to the same figure (this can be achieved using the hold command) in a
different colour a graph of the same function sampled at 5 Hz, using the stem
command.
Using the plot command for a single plot and the hold commands, plot y = sin(x) and
y = cos(x) on the same graph for values of x defined by: x = 0:pi/30:2*pi
Using the ezplot command, plot y = 2 3 sin(9πx), for values of x such that 0 ≤ x ≤ 2 ∗ pi
APPLICATIONS
Plot functions are used in the signal processing application to analyze the signal
attributes
3D Plot functions are used in the material stress and strain analysis to view stress/strain
distribution on the material
Plot functions are used in the Electrical and Electronics domain to analyze the domain
attributes
In Control System domain, the plot functions are used to analyze the stability and
dynamics of the systems
Plot functions are used to analyze the colour pixel value distribution in the Image
processing applications
CONCLUSION
The data are visualized as a 2D and 3D plot and changing its associative parameters
practiced.
89
11. DESIGN A SIMPLE DIGITAL CIRCUITS (ADDER) USING
SIMULINK
AIM:
DESCRIPTION
In this experiment, the digital circuit simulation using MATLAB Simulink is demonstrated.
The exercise provide the overview on access the necessary simulation blocks for digital circuit
simulation and also demonstrate the verification method for the developed digital circuit.
EXCERCISE
90
TABLE 10.1 Truth table full adders
Ai Bi Ci-1 Si Ci
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1
LEARNING OUTCOMES
The student will be able to apply the Simulink for digital circuit design and verification.
The student will be able to design and verify the engineering fundamentals, and an
engineering specific concepts
VIVA QUESTIONS
1. How to export the Simulink variable to the workspace?
2. Mention the method to call the M script file in the Simulink.
3. How will you burn the Simulink code into the target board?
4. Compare the Simulink and M file functions in MATLAB.
5. How will you implement the lookup table in Simulink to verify the digital logic circuits?
6. List out the number functions available to simulate the digital input in the Simulink.
7. Mention the parameters available to configure the digital signals.
8. How will you change the simulation time in the Simulink?
9. Mention the functions available in the scope function to configure the plot.
10. How will you export the graph variables to the workspace?
EXERCISE
Simulate and verify the half adder digital circuit
Simulate the RLC circuit using MATLAB m script and plot the frequency response
Simulate and verify the amplification circuit using operational amplifier
APPLICATIONS
Analog circuit design and implementation
MATLAB Simscape is used to design, simulate and deploy for the electrical application
MATLAB m script and Simulink are used to deploy and verify the circuit analysis
methods
MATLAB Simulink is used to simulate, verify and deploy the electronic circuit
MATLAB m script is used to simulate and verify the mathematical model of the
electronic and electrical circuits
CONCLUSION
The half adder digital circuit was designed and verified using MATALB Simulink.
91
12. APP DESIGNER USING MATLAB
AIM
To design a desktop application for the given application using MATLAB App designer.
DESCRIPTION
In this experiment, the creation of MATLAB App designer for an application demonstrated.
The exercise provide the overview on configuring input options, output options and add graph,
video display in the MATLAB App designer.
EXERCISE
• The function Create Components contains all the code to produce all the graphical
objects
specified in the Design View of the App Designer. At the top, the figure is created.
92
• The Main App Function
• Below Create Components is the main app function. This is what executes when
you run the app.
• It does two things: Calls Create Components and registers the app.
• The last function is the delete function which tidies things up when the app is
deleted.
• To make it possible to interact with the graphics, many of the graphical objects look for
particular events to occur. You can configure an object to run a Callback Function when
an event happens
• Take for example the Celsius Edit Field on the temperature converter.
• When somebody enters a temperature into the Edit Field, we want the app to display the
temperature in Fahrenheit in the other Edit Field.
• We get the App Designer to create a Value Changed Callback Function and we add
the following code into the function:
LEARNING OUTCOMES
The student will be able to create MATLAB App for the General Engineering analysis,
Image Processing and Embedded Control applications
The student will be able to apply MATLAB APPP design in an engineering
specialization to the solution of complex engineering problems
93
VIVA QUESTIONS
EXERCISES
Develop a MATLAB App design to plot the temperature value and to trim the plot within
the specified range
Develop a MATLAB App design to display the image and standard tools to apply basic
image processing techniques
Create App design to convert the units of the length as per the user requirement.
APPLICATIONS
MATLAB App designer is used to build Web App applications
App designer is used to develop interactive front end when application required more
configuring options
MATLAB App designer is used to create standalone app to run in the systems, which
does not require MATLAB software to run
App design is used to provide interactive console for the Embedded control applications
App design is used to create interactive display for the Image processing applications
CONCLUSION
Thus the App was created for temperature unit conversion using MATLAB App
designer.
94
APPENDIX 1: MATLAB Installation Guide
Account Creation:
QR CODE:
95
Steps to Install MATLAB:
96
MATLAB Online- use MATLAB in a web browser without
installing, configuring, or managing any software.
https://www.mathworks.com/products/matlab-online.html
97
APPENDIX 2: Self-Paced, Online Training for MATLAB and Simulink
99