0% found this document useful (0 votes)
107 views102 pages

Simulation Laboratory

The document describes the basic components of MATLAB and Simulink. It discusses the MATLAB desktop layout including the command window, current folder, and workspace. It also covers creating variables, calling functions, Simulink block diagrams, creating simple Simulink models, adding and connecting blocks, and refining models. Finally, it provides an overview of various toolboxes available in MATLAB for different applications.
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)
107 views102 pages

Simulation Laboratory

The document describes the basic components of MATLAB and Simulink. It discusses the MATLAB desktop layout including the command window, current folder, and workspace. It also covers creating variables, calling functions, Simulink block diagrams, creating simple Simulink models, adding and connecting blocks, and refining models. Finally, it provides an overview of various toolboxes available in MATLAB for different applications.
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/ 102

SRI RAMAKRISHNA ENGINEERING COLLEGE

COIMBATORE – 641 022.

VISION

To develop into a leading world class Technological University


consisting of Schools of Excellence in various disciplines with a co-
existent Centre for Engineering Solutions Development for world-wide
clientele.

MISSION

To provide all necessary inputs to the students for them to grow into
knowledge engineers and scientists attaining.

 Excellence in domain knowledge- practice and theory.


 Excellence in co-curricular and Extra curricular talents.
 Excellence in character and personality.
SRI RAMAKRISHNA ENGINEERING COLLEGE
[Educational Service : SNR Sons Charitable Trust]
[Autonomous Institution, Accredited by NAAC with ‘A’ Grade]
[Approved by AICTE and Permanently Affiliated to Anna University, Chennai]
[ISO 9001:2015 Certified and all eligible programmes Accredited by NBA]
VATTAMALAIPALAYAM, N.G.G.O. COLONY POST,
COIMBATORE – 641 022.
TAMILNADU, INDIA

SIMULATION LABORATORY MANUAL

Prepared by

Dr.K.Srinivasan Dr.B.Sharmila Mr.S.Kaushik


Professor & Head Professor Assistant Professor

In association and collaboration with

1
INDEX

SL
NAME OF THE EXPERIMENT Page No.
.No.

1 COMPONENTS OF COMPUTATIONAL SOFTWARE AND TOOLBOXES 4

2 MATHEMATICAL OPERATIONS USING ARRAYS AND MATRICES 30

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

11 DESIGN A SIMPLE DIGITAL CIRCUITS (ADDER) USING SIMULINK 90

12 APP DESIGNER USING MATLAB 92

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.

Fig 1.1 Layout of MATLAB

The desktop includes these panels:

 Current Folder — To access your files.

 Command Window — To Enter commands at the command line, indicated by the

prompt symbol (>>) and to display the result.


4
 Workspace — To view, create, save, edit the data or import the data from files.

PRACTICE EXERCISES:

1.1 Commands that create variables and call functions:


 Create a variable named a by typing this statement at the command line:

>> a = 1

MATLAB adds variable ‘a’ to the workspace and displays the result in the Command Window.

>> a = 1

 Create a few more variables.

>> 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

Fig 1.2 Workspace window in MATLAB

 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.

 Restore data from a MAT-file into the workspace using load.

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.

 To call a function, such as max, enclose its input arguments in parentheses:

>> A = [1 3 5];
>> max(A)
ans = 5
 If there are multiple input arguments, separate them with commas:

>> B = [10 6 4];


>> max(A,B)
ans = 1×3
10 6 5
 Return output from a function by assigning it to a variable:

>> maxA = max(A)


maxA = 5

 When there are multiple output arguments, enclose them in square brackets:

>> [maxA,location] = max(A)


maxA = 5
location = 3
 Enclose any character inputs in single quotes:

>> disp('hello world')


hello world
 To call a function that does not require any inputs and does not return any outputs, type
only the function name:

>> 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.

1.4.1. Simulink Block Diagrams:


Simulink® is a graphical modeling and simulation environment for dynamic systems. You
can create block diagrams, where blocks represent parts of a system. A block can represent a
physical component, a small system, or a function. An input/output relationship fully characterizes
a block. Consider these examples:

 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.

Fig 1.4 Gain block in Simulink to amplify the input signal

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.

Fig 1.5 Simulink file to amplify the sine wave amplitude

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:

Signals - Block inputs and outputs, computed during simulation

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.

1.4.2. Create a Simple Model:


Simulink® can be used to model a system and then simulate the dynamic behavior of that
system. The basic techniques you use to create a simple model in this tutorial are the same as those
you use for more complex models. This example simulates simplified motion of a car. A car is
typically in motion while the gas pedal is pressed. After the pedal is released, the car idles and
comes to a stop.

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

Table I Simulation blocks required to create simple Simulink model

Block Name Block Purpose Model Purpose


Pulse Generator Generate an input signal for the Represent the accelerator pedal
model
Gain Multiply the input signal by a Calculate how pressing the accelerator
constant value affects the car acceleration
Integrator, Integrate the input signal twice Obtain position from acceleration
Second-Order
Outport Designate a signal as an output Designate the position as an output from the
from the model model

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.4.3 Open New Model


Use the Simulink Editor to build your models.

1. Start MATLAB®. From the MATLAB toolstrip, click the Simulink button .

Fig 1.9 Layout of MATLAB Simulink


12
2. Click the Blank Model template.

The Simulink Editor opens as shown in Fig 1.10

Fig 1.10 Layout of Simulink blank model

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.

1.4.4 Open Simulink Library Browser


Simulink provides a set of block libraries, organized by functionality in the Library Browser. The
following libraries are common to most workflows:

 Continuous — Blocks for systems with continuous states

 Discrete — Blocks for systems with discrete states

 Math Operations — Blocks that implement algebraic and logical equations

 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

Fig 1.11 MATLAB Simulink library

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.4.5 Add Blocks to a Model


To start building the model, browse the library and add the blocks.

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.

Parameter values are held throughout the simulation.

1. Add the following blocks as shown in Table 1.2 to your model using the same approach.

Table 1.2 Simulink blocks for simulation model

Block Library Parameter

Gain Simulink/Math Operations Gain: 2

Integrator, Second-Order Simulink/Continuous Initial condition: 0

Outport Simulink/Sinks Port number: 1

2. Add a second Outport block by copying the existing one and pasting it at another point
using keyboard shortcuts.

3. Your model now has the blocks you need.

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.4.6 Connect Blocks


Connect the blocks by creating lines between output ports and input ports.

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.

Fig 1.14 Connecting pulse signal block to gain block

2. Click the input port of the Gain block.

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

Add Signal Viewer


To view simulation results, connect the first output to a Signal Viewer.

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.

Fig 1.17 Adding Viewer in the output side

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.

Fig 1.18 Stop time shows simulation running time as 10 secs

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.

2. To run the simulation, click the Run button .

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

1.4.7 Refine Model


This example takes an existing model, moving_car.slx, and models a proximity sensor based on
this motion model. In this scenario, a digital sensor measures the distance between the car and an
obstacle 10 m (30 ft) away. The model outputs the sensor measurement and the position of the car,
taking these conditions into consideration:

 The car comes to a hard stop when it reaches the obstacle.

 In the physical world, a sensor measures the distance imprecisely, causing random
numerical errors.

 A digital sensor operates at fixed time intervals.

 To start, open the moving_car model. At the MATLAB command line, enter:

>> open_system ('moving_car.slx')

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.

Add New Blocks and Connections

Add a sensor that measures the distance from the obstacle.

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.

Fig 1.21 To create a branch in the Simulink model

Annotate Signals

Add signal names to the model.

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

2. To finish, click away from the text box.

3. Repeat these steps to add the names as shown Fig 1.23.

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.

Fig 1.24 Adding scope in the Simulink model

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.

Fig 1.26 Zoom the signal in scope window

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

1. What is MATLAB? Where the MATLAB can be applicable?


2. List out the layout options in the MATLAB.
3. Infer the differences of Simulink and M script.
4. Point out the steps to be followed to implement the function in the M-file
5. List out the standard toolboxes present in MATLAB and how these toolboxes can be
accessed.
6. Mention the purpose of command prompt.
7. Compare the convenient features available with M file when compared to Simulink
8. How will you modify the parameters like simulation time, ode solver in the Simulink?
9. Is there any limit to pass the number of parameters in M file as function?
10. Where to access the variable data that are created in the Simulink?

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

This type of array is a row vector.


 To create a matrix that has multiple rows, separate the rows with semicolons.
>> a = [1 2 3; 4 5 6; 7 8 10]
a = 3×3
1 2 3
4 5 6
7 8 10

 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

To transpose a matrix, use a single quote ('):


>> a'
ans = 3×3
1 4 7
2 5 8
3 6 10

 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

 Reset the display to the shorter format using


>> format short

format affects only the display of numbers, not the way MATLAB computes or saves them.

 To perform element-wise multiplication rather than matrix multiplication, use


the .* operator:
>> p = a.*a
p = 3×3
1 4 9
16 25 36
49 64 100

 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

 To represent the imaginary part of complex numbers, use either i or j.


>> c = [3+4i, 4+3j; -i, 10j]
c = 2×2 complex
3.0000 + 4.0000i 4.0000 + 3.0000i
0.0000 - 1.0000i 0.0000 +10.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

 There are two ways to refer to a particular element in an array.


 Specify row and column subscripts
>> A(4,2)
ans = 14

 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

Creating, Concatenating, and Expanding Matrices


The most basic MATLAB® data structure is the matrix. A matrix is a two-dimensional, rectangular
array of data elements arranged in rows and columns. The elements can be numbers, logical values
(true or false), dates and times, strings, or some other MATLAB data type.
Even a single number is stored as a matrix.
 A variable containing the value 100 is stored as a 1-by-1 matrix of type double.
>> A = 100;
>> whos A

34
Name Size Bytes Class Attributes
A 1x1 8 double

2.3 Constructing a Matrix of Data


A single row of data has spaces or commas in between the elements, and a semicolon separates
the rows.
 Create a single row of four numeric elements. The size of the resulting matrix is 1-by-4,
since it has one row and four columns. A matrix of this shape is often referred to as a row
vector.
>> A = [12 62 93 -8]

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

2.5 Concatenating Matrices


Use square brackets to join existing matrices together. This way of creating a matrix is
called concatenation.
 Concatenate two row vectors to make an even longer row vector.
>> A = ones(1,4);
>> B = zeros(1,4);
>> C = [A B]

C = 1×8
1 1 1 1 0 0 0 0

 Arrange A and B as two rows of a matrix, use the semicolon.


D = [A;B]

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

 An alternative way to concatenate matrices is to use concatenation functions such


as horzcat, which horizontally concatenates two compatible input matrices.
>> D = horzcat(A,B)

D = 2×5
1 1 1 0 0
1 1 1 0 0

Generating a Numeric Sequence


The colon is a handy way to create matrices whose elements are sequential and evenly spaced.
 Create a row vector whose elements are the integers from 1 to 10.
>> A = 1:10
A = 1×10
1 2 3 4 5 6 7 8 9 10

 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

 Decrement, use a negative number


>> A = 6:-1:0
A = 1×7
6 5 4 3 2 1 0

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

2.6 Expanding a Matrix


Add one or more elements to a matrix by placing them outside of the existing row and column
index boundaries. MATLAB automatically pads the matrix with zeros to keep it rectangular.
 Create a 2-by-3 matrix and add an additional row and column to it by inserting an element
in the (3,4) position.
>> A = [10 20 30; 60 70 80]
A = 2×3
10 20 30
60 70 80

>> 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

Text in String and Character Arrays


 There are two ways to represent text in MATLAB®.
o String Arrays.
o Character Arrays.
 A typical use for character arrays is to store pieces of text as character
vectors.
 MATLAB displays strings with double quotes and character vectors with single quotes.

Represent Text with String Arrays

When you are working with text, enclose sequences of characters in double quotes. You can assign
text to a variable.

>> t = "Hello, world";


If the text includes double quotes, use two double quotes within the definition.

>> q = "Something ""quoted"" and something else."


q=
"Something "quoted" and something else."
t and q are arrays, like all MATLAB® variables. Their class or data type is string.

>> 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.

>> str = "They said, ""Welcome!"" and waved."


>> fahrenheit = 71;
>> celsius = (fahrenheit-32)/1.8;
>> tempText = "temperature is " + celsius + "C"
>> tempText2 = append("Today's ",tempText)
str =
"They said, "Welcome!" and waved."
tempText =
"temperature is 21.6667C"
tempText2 =
"Today's temperature is 21.6667C"

The string function can convert different types of inputs, such as numeric, datetime, duration,
and categorical values.

 Convert the output of pi to a string.


>> ps = string(pi)
ps =
"3.1416"

 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.

 Find the lengths of the strings with the strlength function.

>> str = ["Mercury","Gemini","Apollo"; "Skylab","Skylab B","ISS"]


>> N = strlength(str)

str = 2x3 string


"Mercury" "Gemini" "Apollo"
"Skylab" "Skylab B" "ISS"
str is a 2-by-3 string array.

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.

>> chr = 'Hello, world'


chr =
'Hello, world'

 The text 'Hello, world' is 12 characters long, and chr stores it as a 1-by-12 character
vector.

>> whos chr


Name Size Bytes Class Attributes
chr 1x12 24 char

 The text includes single quotes, use two single quotes.

>> chr = 'They said, ''Welcome!'' and waved.'


chr =
'They said, 'Welcome!' and waved.'

Character vectors have two principle uses:


 To specify single pieces of text, such as file names and plot labels.
 To represent data that is encoded using characters.
 Store a DNA sequence as a character vector and access individual characters or subsets of
characters by indexing

>> seq = 'GCTAGAATCC';


>> seq(4:6)

ans =
'AGA'

 Concatenate character vector with square brackets, just as you concatenate other types of
arrays.

>> seq2 = [seq 'ATTAGAAACC']


seq2 =
'GCTAGAATCCATTAGAAACC'

 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

>> seq2 = append(seq,'ATTAGAAACC')


seq2 =
'GCTAGAATCCATTAGAAACC'
42
 Create two strings and combine strings using append

>> str1 = "Good";


>> str2 = "Morning";
>> str = append(str1,str2)
str =
"GoodMorning"

 Add a space between the input strings, specify a space character as another input argument.

>> str = append(str1,' ',str2)


str =
"Good Morning"

 Use the plus operator to combine strings.

>> str = str1 + ' ' + str2


str =
"Good Morning"

Combine Character Vectors


 Create and combine two character vectors

>> chr1 = 'Hello ';


>> chr2 = 'World';
>> chr3 = append(chr1,chr2)
chr3 =
'Hello World'

 Use append function always preserves trailing whitespace characters, unlike


the strcat function. (strcat removes trailing whitespace characters from character
vectors.)

>> chr4 = strcat(chr1,chr2)


chr4 =
'HelloWorld'

Combine Arrays of Text


Combine string arrays or cell arrays of character vectors, element by element. Also, append a
single piece of text to the elements of an input array.

 Create an array of file names.

>> names = ["data" "report" "slides"]


names = 1x3 string
"data" "report" "slides"

43
 Create an array of file extension names, with a different extension for each element
of names.

>> ext = [".xlsx" ".docx" ".pptx"]


ext = 1x3 string
".xlsx" ".docx" ".pptx"

 Combine the file names and extensions.

>> str1 = append(names,ext)


str1 = 1x3 string
"data.xlsx" "report.docx" "slides.pptx"

 Append the same extension to each name, use a character vector or a string scalar.

>> str2 = append(names,'.mat')


str2 = 1x3 string
"data.mat" "report.mat" "slides.mat"

Implicit Expansion

The append function supports implicit expansion of arrays.


 Combine strings from a column vector and a row vector to form a two-dimensional string
array.
 Create a column vector of strings. Then create a row vector. Combine str1 and str2.

>> str1 = ["A";"B";"C"]


>> str2 = ["1" "2" "3" "4"]
>> str = append(str1,str2)
str1 = 3x1 string
"A"
"B"
"C"
str2 = 1x4 string
"1" "2" "3" "4"

str = 3x4 string


"A1" "A2" "A3" "A4"
"B1" "B2" "B3" "B4"
"C1" "C2" "C3" "C4"

44
Split String and Find Unique Words

 Find the unique words in a string, split it on space characters and call the unique function.

Create a string scalar.


>> str = "A horse! A horse! My kingdom for a horse!"
str =
"A horse! A horse! My kingdom for a horse!"

Remove the exclamation point.


>> str = erase(str,"!")
str =
"A horse A horse My kingdom for a horse"

Convert all letters in str to lowercase characters.


>> str = lower(str)
str =
"a horse a horse my kingdom for a horse"

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"

Find the unique words in str using the unique function.


>> str = unique(str)
str = 5x1 string
"a"
"for"
"horse"
"kingdom"
"my"

Convert Character Vector


>> A = 'Four score and seven years ago'
A=
'Four score and seven years ago'

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

Return the number of characters in str, use the strlength function.


>> n = strlength(str)
n = 30

Convert Cell Array


 Convert a cell array of character vectors to a string array.

>> A = {'Mercury','Gemini','Apollo'; Skylab','Skylab B','ISS'}


>> str = string(A)
A = 2x3 cell
{'Mercury'} {'Gemini' } {'Apollo'}
{'Skylab' } {'Skylab B'} {'ISS' }
str = 2x3 string
"Mercury" "Gemini" "Apollo"
"Skylab" "Skylab B" "ISS"
 Access the second element in the first row of str, index using smooth parentheses using
with matrix indexing.
>> str(1,2)
ans =
"Gemini"
 Access the third column.
>> str(:,3)
ans = 2x1 string
"Apollo"
"ISS"

Convert Numeric Array

>> A = [77 65 84 76 65 66]


>> str = string(A)
A = 1×6
77 65 84 76 65 66
str = 1x6 string
"77" "65" "84" "76" "65" "66"
46
str is a string array in which each element represents a number from A.
Note that string does not treat numbers as ASCII or Unicode values the way that
the char function does.

Convert Strings That Represent Numbers


 Create a string array in which each element represents a number. Convert the string array
to a numeric array, use the double function.

>> str = ["256","3.1416","8.9e-3"]


>> X = double(str)
str = 1x3 string
"256" "3.1416" "8.9e-3"
X = 1×3
256.0000 3.1416 0.0089

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

Convert Duration Array


 Create a duration array. Convert D to a string array.

>> D = hours(23:25) + minutes(8) + seconds(1.2345)


>> str = string(D)

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.

 Specify the format of the duration values in str.

>> str = string(D,'hh:mm')


str = 1x3 string
"23:08" "24:08" "25:08"

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.

>> str = "Hello, World"


>> L = strlength(str)
str =
"Hello, World"
L = 12

Length of Each String in String Array


 Create a string array using the [] operator. str is a 2-by-3 string array that contains six
strings. Find the length of each string in str. Use strlength, not length, to determine
the number of characters in each element of a string array.

>> str = ["Amis","Chekhov","Joyce";"Stein","","Proust"]


>> L = strlength(str)
str = 2x3 string
"Amis" "Chekhov" "Joyce"
"Stein" "" "Proust"
L = 2×3
4 7 5
5 0 6

Number of Characters in Character Vector


 Create a character vector. To return the number of characters in the character vector, use
the strlength function.

>> chr = 'The rain in Spain.'


>> L = strlength(chr)
chr =
'The rain in Spain.'
L = 18

Determine if Array Contains String Values


 Create different arrays, and then determine if they are string arrays. Test a character vector.

>> chr = 'Mary Jones'


>> tf = isstring(chr)
chr =
'Mary Jones'
tf = logical
0

48
Character vectors are not strings, so isstring returns 0.
 Test a string array

>> str = ["Smith","Chung","Morales"; "Sanchez","Peterson","Adams"]


>> tf = isstring(str)
str = 2x3 string
"Smith" "Chung" "Morales"
"Sanchez" "Peterson" "Adams"
tf = logical
1
str is a string array, so isstring returns 1.

Numeric Values
 Convert numeric value to strings

>> X=[5 10 20 3.1416]


>> string(X)
X = 1×4
5.0000 10.0000 20.0000 3.1416
ans = 1×4 string array
"5" "10" "20" "3.1416"

 Convert datetime value to strings

>> d=datetime('now');
>> string(d)
ans = "20-Feb-2020 09:27:55"

Create a character array to store data

 Convert integer to characters


>> a=[77 65 84 76 65 66]
>> b=char(a)
a = 1×6
77 65 84 76 65 66
b = 'MATLAB'

 Convert multiple array to charcter array


>> c=[77 65 84;76 65 66]
>> d=char(c)
c = 2×3
77 65 84
76 65 66
d = 2×3 char array
'MAT'
'LAB'

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

u 1x3 24 double array


v 1x3 24 double array

Grand total is 6 elements using 48 bytes

>> save sample.mat


>> ls
sample.mat

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

u 1x3 24 double array


v 1x3 24 double array

Grand total is 6 elements using 48 bytes

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);

Figure 4.1 Image displayed using importdata command

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

>> filename = ‘weeklydata.txt’;


>> delimiterIn = ‘ ‘;
>> headerlinesIn = 1;
>> A = importdata(filename,delimiterIn,headerlinesIn);
>> % View data of first column
>> for k = [1:1]
>> disp(A.colheaders{1, k})
>> disp(A.data(:, k))
>> disp(‘ ‘)
>> end

SunDay
95.0100
73.1100
60.6800
48.6000
89.1300

To view data of first two columns

>> filename = ‘weeklydata.txt’;


>> delimiterIn = ‘ ‘;
>> headerlinesIn = 1;
>> A = importdata(filename,delimiterIn,headerlinesIn);
>> % View data of first two columns
>> for k = [1:1]
>> disp(A.colheaders{1, k})
>> disp(A.data(:, k))
>> disp(‘ ‘)

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.

Times in sec Temperature in ⸰C


0 22.8
15 26.9
30 26.8
60 26.8
90 26.8
120 26.7
150 26.7
180 26.7
210 26.7
240 26.6
270 26.6
300 26.6
330 26.6

 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');

Fig 6.1 Data plotted using plot function


>> loglog(x,y);
>> title('log');

Fig 6.2 Data plotted using log function

57
>> stackedplot(x,y); title('stackedplot');

Fig 6.3 Data plotted using stackedplot function


>> stairs(x,y);
>> title('stairs');

Fig 6.4 Data plotted using stairs function

>> semilogx(x,y);
>> title('semilog');

Fig 6.5 Data plotted using semilog function


>> area(x,y);
>> title('area');
58
Fig 6.6 Data plotted using area function
>> semilogy(x,y);
>> title('semilogy');

Fig 6.7 Data plotted using semilog function


>> pie(x,y);
>> title('piechart');

Fig 6.8 Data plotted using semilog function


>> scatter(x,y);
>> title('scatter');

59
Fig 6.9 Data plotted using scatter function

>> plotmatrix(x,y);
>> title('plotmatrix');

Fig 6.10 Data plotted using plotmatrix function

comet(x,y);
title('comet');

Fig 6.11 Data plotted using comet function


>> bar(x,y)
>> title('bar');

60
Fig 6.12 Data plotted using bar function
>> barh(x,y);
>> title('horizontalbar');

Fig 6.13 Data plotted using horizontal bar function

>> pareto(y,x);
>> title('paretochart');

Fig 6.14 Data plotted using pareto function


>> stem(x,y);
>> title('stem');

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

 Using the command prompt


 Using the IDE
If you are using the command prompt, type edit in the command prompt. This will open the
editor. You can directly type edit and then the filename (with .m extension)
>> edit
or
>> edit <filename>
The above command will create the file in default MATLAB directory. If you want to store all
program files in a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command prompt (>>)
mkdir progs % create directory progs under default directory
chdir progs % changing the current directory to progs
edit prog1.m % creating an m file named prog1.m
If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.

Fig 6.1 Layout of the M script file

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

Create and plot a sphere with radius r


% Create and plot a sphere with radius r.
[x,y,z] = sphere; % Create a unit sphere.
r = 2;
surf(x*r,y*r,z*r) % Adjust each dimension and plot.
axis equal % Use the same scale for each axis.
% Find the surface area and volume.
A = 4*pi*r^2;
V = (4/3)*pi*r^3;
Save the file in the current folder. To run the script, type its name at the command line:

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

Fig 6.2 Sphere drawn using plot function


64
Create a function file, named mymax.m and type the following code in it

function max = mymax(n1, n2, n3, n4, n5)


% This function calculates the maximum of the
% Five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end

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

Example 1: Convert script to Live Script


 For example, convert mysphere to a live script by selecting Save As and changing the file
type to a MATLAB live code file (*.mlx). Then, replace the code comments with formatted
text. For instance:
 Convert the comment lines to text. Select each line that begins with a percent symbol, and

then select Text, . Remove the percent symbols.

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.

Fig 6.3 Layout of Live Script

To create a new live script using the edit command, include the .mlx extension with the file name:

>> edit newfile.mlx


Example 2 : Basic Plot
Type the following code
n = 50;
r = rand(n,1);
plot(r)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')

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

>> % Basic programs using if


>> A=10;
>> B=5;
>> if A>B
>> disp('A is greater')
>> end
A is greater
>> % Basic programs using if else
>> C=15;
>> D=20;
>> if D>C
>> disp('D is greater')
>> else
>> disp('C is greater')
>> end
D is greater
>> % Basic programs using elseif
>> E=randi(100,1)
E = 82

>> if E<30
69
>> disp('small')
>> elseif E<80
>> disp('medium')
>> else
>> disp('large')
>> end
large

%if statement for finding palindrome


>> string=input('Enter a string:', 's')
>> string = 'matlab'
>> if string==fliplr(string)
>> disp("Palindrome")
>> else
>> disp("NOT A Palindrome")
>> end
NOT A Palindrome

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

%for loop for reversing a string


>> str="matlab"
>> ch=char(str)
>> newstr=string(ch(end:1:1))
>> newch=[]
>> for i=1:length(ch)
>> newch=[newch,ch(end-i+1)]
>> end
str = "matlab"
ch = 'matlab'
newstr = 1×0 empty char array
newch = []
newch = 'b'

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;

%Use equationsToMatrix to convert the equations into the form AX = B.


[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])
Command Prompt
>>
A=

B=

%Use linsolve to solve AX = B for the vector of unknowns P.


>> P = linsolve(A,B)
P=

%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')

Fig 8.1 Plot graph of van der Pol equation

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

Fig 8.2 Plot graph of interpolation

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)

Fig 8.3 Plot graph of interpolation after normalization

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

Converting Equation to Matrix


>> syms x y z
>> eqns = [x-y+2*z == -3,
>> x+2*y+3*z == 4,
>> 2*x+y+z == -3];
>> [A,b] = equationsToMatrix(eqns)
>> vars = symvar(eqns)
A=

[ 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

>> % Declare the array


>> A=[1 -1 2; 1 2 3; 2 1 1];
>> b= [-3; 4; -3];

>> %start the program


>> % check for singularity
>> if det(A)==0
error('MAtrix is singular')
end

>> [i,j]=size(A);

>> for k = 1 : i % k will loop from 1 to 3

B=A; % set array B to array A


B(:,k)=b; % replace relevant col with RHS
det(B); % display det of B
x(k)=det(B)/det(A); % solve for unknowns
end

>> fprintf('The solution to x is %0.2f \n',x(1))


>> fprintf('The solution to y is %0.2f \n',x(2))
>> fprintf('The solution to z is %0.2f \n',x(3))

The solution to x is -3.00


The solution to y is 2.00
The solution to z is 1.00

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

>> ezsurf(z1,[-2 2])

Fig 9.1 Representation of equation x+2y-1 using ezsurf

>> z2=@(x,y) x+y-2

z2 =
function_handle with value:
@(x,y)x+y-2

>> ezsurf(z2,[-2 2])

Fig 9.2 Representation of equation x+y-2 using ezsurf

82
>> z3=@(x,y) y-x

z3 =
function_handle with value:
@(x,y)y-x

>> ezsurf(z3,[-2 2])

Fig 9.3 Representation of equation y-x using ezsurf

Merging all 3 planes in one graph

Fig 9.3 Intersection of three planes in one point

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])

S = struct with fields:


u: [1x1 sym]
v: [1x1 sym]
>> S.u
ans =
1/3
>> S.v
ans =
−2/3
LEARNING OUTCOMES

 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

 Solve this system of linear equations in matrix form by using linsolve.

 Solve the system of equations. 2u2+v2=0 and u−v=1


 The solve function can solve inequalities and return solutions that satisfy the

inequalities. Solve the following inequalities. x>0, y>0, x2+y2+xy<1

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:

%% Creating 2-D Plots


% Show how to create 2-D line plots in MATLAB using the plot function.
% Create a regularly-spaced vector x from 0 to 2*pi using pi/100 as the increment between
elements.
x = 0:pi/100:2*pi;
% Calculate sine for each value in x.
y = sin(x);
% Use the figure command to create a new figure and plot command to display result.
figure;
plot(x, y)
% Label the axes and add a title so that viewers understand the purpose of your graph.
xlabel('x')
ylabel('sin(x)')
title('Plot of the Sine Function')

Fig 10.1 Simple plot graph for sine wave

% 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:

To design a full adder digital circuit using MATLAB Simulink.

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

Fig 10.1 Full adder circuit using MATLAB Simulink

Fig 10.2 Output of full adder circuit shown in Simulink Scope

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

Fig 11.1 Layout of MATLAB App designer

• 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.

% Create Temperature Converter UI Figure


app.TemperatureConverterUIFigure = uifigure;
app.TemperatureConverterUIFigure.Position = [100 100 251 239];
app.TemperatureConverterUIFigure.Name = ‘Temperature Converter’;

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 Delete Function

• 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:

C = app.CelsiusEditField.Value; % Get the number from Edit Field


F = C*9/5+32;
App. FahrenheitEditField.Value = F;
• Then we add a Value Changed Callback Function for the Fahrenheit Edit Field

F = app.FahrenheitEditField.Value; % Get number from Edit Field


C = (F 0 32)*5/9;
App.CelsiusEditField.Value = C;
 The final app output will look like as shown in the Fig 11.1

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

1. List the number of input graphics available in the App design.


2. Mention the graph functions handled by the App design.
3. How will you convert the App design into a stand alone software?
4. Compare App design and Simulink in MATLAB
5. List the calling functions available in the App design.
6. Identify whether the M file commands can be inserted in the App design.
7. Identify the parameters used to configure the Input and Output in the App design
8. Compare the App design and guide in the MATLAB
9. Identify whether the App design can communicate with the hardware platform.
10. Mention the method to develop code in the App design platform.

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:

To associate to the Campus-Wide License, Open the Sri


Ramakrishna Engineering College MATLAB Portal or simply
scan the QR Code :

1. Click on Sign-In to get started


2. Sign in using your MathWorks Account with your Sri
Ramakrishna Engineering College email address.
3. If you do not have a MathWorks Account with your Sri
Ramakrishna Engineering College email address, click on
Create Account
4. Complete the steps to create your MathWorks Account (If
you have any trouble creating an account, contact
MathWorks Customer Service via [email protected] or +
91-80-6632-6000)
5. Once logged in on the Portal, you would automatically be
associated to the Sri Ramakrishna Engineering College Sri
Ramakrishna Engineering College MATLAB Campus-
Wide License.

QR CODE:

95
Steps to Install MATLAB:

• Click the download button for the current release. (Users


can also download previous releases here).
• Choose a supported platform and download the installer.
• Run the installer.
• In the installer, select Log in with a MathWorks Account
and follow the online instructions.
• When prompted to do so, select the Academic – Total
Headcount license labeled Individual.
• Select the products you want to download and install.
• After downloading and installing your products, keep the
Activate MATLAB checkbox selected and click Next.
• Select “Activate automatically using the internet”.
• Log into your MathWorks account
• Select the Academic – Total Headcount license labeled
Individual.
• Click "finish" to complete the activation process.

For any installation issues, contact the MathWorks Install Support


team at: [email protected] or call + 91-80-6632-6000 (Option 3).

96
MATLAB Online- use MATLAB in a web browser without
installing, configuring, or managing any software.
https://www.mathworks.com/products/matlab-online.html

MATLAB Mobile- evaluate MATLAB commands, create and


edit files, visualize data, and view results – all from your iPhone,
iPad, or Android device.
https://www.mathworks.com/products/matlab-mobile.html

97
APPENDIX 2: Self-Paced, Online Training for MATLAB and Simulink

Steps to Access the MATLAB Training Courses:


1. Go to MATLAB Portal or https://matlabacademy.mathworks.com/
2. Login to the MathWorks Account.
3. Click on Launch to start the Course.

Note: Course Completion certificate provided upon completing


the Each course.
98
Product List R2020b

99

You might also like