Network modeling, simulation and analysis in Matlab theory and practices 9781119631385, 1119631386, 9781119631453, 1119631459, 9781119631477, 1119631475

"The purpose of this book is first to study MATLAB programming concepts, then the basic concepts of modeling and si

337 99 10MB

English Pages [367] Year 2019

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Title Page......Page 5
Copyright Page......Page 6
Contents......Page 7
List of Figures......Page 13
List of Tables......Page 17
Foreword......Page 19
Preface......Page 21
Acknowledgments......Page 23
Acronyms......Page 25
1 Introduction to Modeling, Simulations and Analysis......Page 29
1.1 MATLAB Modeling and Simulation......Page 30
1.2.1 Computer-Based Models......Page 32
1.2.2 Computer Network Simulation......Page 33
1.3 Discrete-Event Simulation for MATLAB......Page 34
1.3.1 Terminology and Components of Discrete-Event Simulation......Page 35
1.3.2 The Principle of Discrete-Event Simulation......Page 36
1.3.3 ESTA Algorithm......Page 37
1.4 Simulation Software Selection for MATLAB......Page 39
1.5 Simulation Tools Based on High Performance......Page 40
1.5.1 Network Model......Page 41
1.5.2 Network Simulators......Page 43
1.6 Conclusion......Page 50
References......Page 51
2 Introduction to MATLAB Programming......Page 53
2.1 Introduction......Page 54
2.3.1 Practical Examples for MATLAB......Page 55
2.3.2 Use of Semicolon (;) in MATLAB......Page 56
2.3.4 Commonly Utilized Operators and Special Characters......Page 57
2.3.7 MATLAB Decisions......Page 58
2.3.8 MATLAB Loops......Page 59
2.4.1 Import Data in MATLAB......Page 60
2.4.2 Export Data in MATLAB......Page 66
2.5.1 Commands......Page 68
2.5.2 MATLAB Basics......Page 69
2.5.4 Framework Operations......Page 70
2.5.5 Using M-Files......Page 72
2.6 Plotting......Page 75
2.6.1 Including Various Types of Graphs......Page 76
2.6.2 Creation of a Multiple Number of Functions in a Similar Graph......Page 77
2.6.3 Creating a Graph According to Various Colors......Page 78
2.7 Uncommon Function......Page 79
2.8 Executable Files Generation......Page 80
2.9 Calling and Accumulating Executable Documents......Page 82
2.10 Calling Objects from External Programs......Page 83
2.12 The Guide......Page 84
2.12.1 Open a New User Interface......Page 85
2.12.3 Design the User Interface......Page 86
2.12.4 Adjust the Components......Page 87
2.12.5 Mark the Push Buttons......Page 88
2.12.7 Static Test Alteration Procedure in MATLAB......Page 89
2.12.8 Spare the Layout......Page 90
2.12.10 Produce Data to Plot in MATLAB......Page 91
2.12.11 Pop-Up Menu Characteristics......Page 93
2.12.12 Behavior of Push Button......Page 94
2.13 Effective Programming through MATLAB......Page 95
2.13.2 Practice Programs......Page 96
2.14.1 GNU Octave......Page 97
2.14.3 Sage......Page 98
2.15.1 Run a Batch Job......Page 99
2.15.2 Run a Batch Parallel Loop......Page 100
2.15.3 Current Folder Browser - Run Script as Batch Job......Page 101
2.16 Conclusion......Page 102
References......Page 103
3 Digital Communication System Simulation Using MATLAB......Page 105
3.1.1 Data Transmission......Page 106
3.1.2 Example......Page 107
3.1.3 The Conversion of Analog and Digital Signals......Page 108
3.1.4 Information, Bandwidth, and Noise......Page 110
3.2.1 Rayleigh Fading Basics......Page 111
3.2.2 Rayleigh Fading......Page 112
3.3.1 BPSK Modulation......Page 114
3.3.2 BPSK Demodulation......Page 115
3.4 QPSK Modulation and Demodulation......Page 117
3.4.1 QPSK Transmitter......Page 118
3.4.3 Performance Simulation over AWGN......Page 121
3.5.1 M-QAM Modulation......Page 122
3.5.2 Baseband Rectangular M-QAM Modulator......Page 123
3.6 Recreation of OFDM Framework......Page 127
3.6.2 Impact of Cyclic Prefix on Es /N......Page 129
3.6.3 Effect of Unused Subcarriers on Es/N......Page 130
3.6.5 MATLAB Sample Code......Page 131
3.7 Conclusion......Page 136
References......Page 137
4 Statistical Analysis of Network Data Using MATLAB......Page 139
4.1 Introduction to Association Networks......Page 140
4.2.1 Time Series Analysis......Page 142
4.2.2 Stationarity......Page 143
4.2.3 Time Series Decomposition......Page 145
4.2.4 De-trending......Page 146
4.3.1 Autocorrelation......Page 152
4.3.2 ACF and IACF Parameters......Page 154
4.3.3 Test of Independence......Page 156
4.3.4 Linear Autoregressive Models......Page 163
4.3.5 Linear Prediction and Autoregressive Modeling......Page 165
4.4.1 Testing the Significance of the Null Hypothesis I(X; Y ) = 0......Page 167
4.4.2 Producing the Mutual Information Distribution from Surrogates......Page 169
4.5.1 Cross Correlation......Page 171
4.5.2 Vector Autoregression (VAR) Models......Page 174
4.5.3 Coupled Dynamical Systems......Page 177
References......Page 178
5 Network Routing Simulation Using MATLAB......Page 183
5.1 Evaluation of Granger Causality Measures on Known Systems......Page 184
5.1.1 A Historical Viewpoint......Page 186
5.1.2 Application to Recreated Information......Page 192
5.1.3 Application to FMRI BOLD Information from a Visuospatial Consideration Undertaking......Page 198
5.2.1 Objectives......Page 201
5.2.2 Approach to Model Development......Page 202
5.2.3 Development of Models......Page 203
5.2.4 Outline of Findings from Phase Two: Model Validation......Page 204
5.3.1 Genetic Algorithm for Improvement Utilizing MATLAB......Page 206
5.3.2 Masses Diversity-Measure-Run, Prosperity Scaling......Page 210
5.4 Acoustic-Centric and Radio-Centric Algorithms......Page 218
5.5 AODV Routing Protocol......Page 222
5.5.2 Association Breaks......Page 224
5.5.4 Security Considerations......Page 225
5.6 Conclusion......Page 231
References......Page 232
6 Wireless Network Simulation Using MATLAB......Page 237
6.1.3 Small-Scale Blurring......Page 238
6.1.4 Free-Space Propagation......Page 239
6.1.5 Ray Tracing......Page 240
6.1.6 Indoor Propagation......Page 248
6.1.8 COST 231-Hata Model......Page 249
6.1.9 COST 231-Walfish-Ikegami Model......Page 250
6.1.10 Erceg Model......Page 252
6.1.11 Multiple Slope Models......Page 253
6.2.1 Random Waypoint Model......Page 262
6.3 PHY: SNR-Based Bundle Catches, Communication, Dynamic Transmission Rate and Power......Page 263
6.3.1 MAC: IEEE 802.11......Page 264
6.3.2 IEEE 802.11 RTS/CTS Exchange......Page 265
6.4 NET: Ad Hoc Routing......Page 266
6.4.1 Dynamic Destination Sequenced Distance Vector......Page 268
6.4.3 Global State Routing......Page 271
6.4.5 Hierarchical State Routing......Page 272
6.4.6 Zone-Based Hierarchical Link State Routing Protocol......Page 273
6.4.7 Clusterhead Gateway Switch Routing Protocol......Page 274
6.4.8 Cluster-Based Routing Protocols......Page 275
6.4.9 Ad Hoc On-Demand Distance Vector Routing......Page 276
6.4.10 Dynamic Source Routing Protocol......Page 277
6.4.11 Temporally Ordered Routing Algorithm......Page 278
6.4.12 Associativity-based Routing......Page 280
6.4.13 Signal Stability Routing......Page 281
6.5.1 System/Application Designs, Optimizations, and Implementations on Overlay Networks......Page 282
6.5.2 Routing Overlays for VoIP......Page 283
6.5.3 Measurement, Modeling, and Improvement of BitTorrent Overlays......Page 284
6.6 Conclusion......Page 287
References......Page 288
7 Mobility Modeling for Vehicular Communication Networks Using MATLAB......Page 295
7.1.1 Transmit and Receive CAN Messages......Page 296
7.1.2 Examine Received Messages......Page 299
7.1.3 CAN Message Reception Callback Function......Page 300
7.2.1 Plan Your Network Installation......Page 302
7.2.4 Setting Up Local Client Access Configuration......Page 303
7.3 Interaction Layer......Page 305
7.3.3 Dynamic Source Routing (DSR)......Page 306
7.3.4 Diagram of Mobility Model......Page 307
7.3.5 Results and Analysis......Page 308
7.3.6 Association Variation Results......Page 310
7.4.1 TCP Transport Protocol......Page 313
7.4.4 Transmission Control Protocol, or TCP......Page 314
7.5 Conclusion......Page 315
References......Page 316
8 Case Studies and Sample Codes......Page 319
8.1 Case Determination and Structure......Page 320
8.1.4 Impediment of the Technique......Page 321
8.1.7 Summing Up from Logical Investigations......Page 322
8.1.9 Related Vocations......Page 323
8.2.2 Construct Boundary Models......Page 324
8.3.1 Case 1: Create a Credit Scorecard Dissent......Page 330
8.3.2 Case 2: Binning Information......Page 332
8.4 Case Study 3: Random Waypoint Mobility Model......Page 334
8.5 Case Study 4: Node localization in Wireless Sensor Network......Page 340
8.6 Case Study 5: LEACH Routing Protocol for a WSN......Page 353
References......Page 362
EULA......Page 367
Recommend Papers

Network modeling, simulation and analysis in Matlab theory and practices
 9781119631385, 1119631386, 9781119631453, 1119631459, 9781119631477, 1119631475

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Network Modeling, Simulation and Analysis in MATLAB

Scrivener Publishing 100 Cummings Center, Suite 541J Beverly, MA 01915-6106 Publishers at Scrivener Martin Scrivener ([email protected]) Phillip Carmical ([email protected])

Network Modeling, Simulation and Analysis in MATLAB Theory and Practices Dac-Nhuong Le Haiphong University, Haiphong, Vietnam

Abhishek Kumar Pandey ACERC, Visiting faculty, Mdsu, Ajmer Rajasthan, India

Sairam Tadepalli AWS Architect, Python Developer, India

Pramod Singh Rathore ACERC, Visiting Faculty, Mdsu Ajmer Rajasthan, India

Jyotir Moy Chatterjee Lord Buddha Education Foundation (APUTI), Kathmandu, Nepal

This edition first published 2019 by John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, USA and Scrivener Publishing LLC, 100 Cummings Center, Suite 541J, Beverly, MA 01915, USA © 2019 Scrivener Publishing LLC For more information about Scrivener publications please visit www.scrivenerpublishing.com. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, except as permitted by law. Advice on how to obtain permission to reuse material from this title is available at http://www.wiley.com/go/permissions. Wiley Global Headquarters 111 River Street, Hoboken, NJ 07030, USA For details of our global editorial offices, customer services, and more information about Wiley products visit us at www.wiley.com. Limit of Liability/Disclaimer of Warranty While the publisher and authors have used their best efforts in preparing this work, they make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives, written sales materials, or promotional statements for this work. The fact that an organization, website, or product is referred to in this work as a citation and/or potential source of further information does not mean that the publisher and authors endorse the information or services the organization, website, or product may provide or recommendations it may make. This work is sold with the understanding that the publisher is not engaged in rendering professional services. The advice and strategies contained herein may not be suitable for your situation. You should consult with a specialist where appropriate. Neither the publisher nor authors shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages. Further, readers should be aware that websites listed in this work may have changed or disappeared between when this work was written and when it is read. Library of Congress Cataloging-in-Publication Data ISBN 978-1-119-63143-9 Cover image: Pixabay.Com Cover design by Russell Richardson Set in size of 11pt and Minion Pro by Manila Typesetting Company, Makati, Philippines Printed in the USA 10 9 8 7 6 5 4 3 2 1

Contents List of Figures

xi

List of Tables

xv

Foreword

xvii

Preface

xix

Acknowledgments

xxi

Acronyms

xxiii

1 Introduction to Modeling, Simulations and Analysis 1.1 MATLAB Modeling and Simulation 1.2 Computer Networks Performance Modeling and Simulation 1.2.1 Computer-Based Models 1.2.2 Computer Network Simulation 1.3 Discrete-Event Simulation for MATLAB 1.3.1 Terminology and Components of Discrete-Event Simulation 1.3.2 The Principle of Discrete-Event Simulation 1.3.3 ESTA Algorithm 1.3.4 ANALYSIS: Determination of Time to Attain Steady State Condition for MATLAB 1.4 Simulation Software Selection for MATLAB 1.5 Simulation Tools Based on High Performance 1.5.1 Network Model 1.5.2 Network Simulators 1.6 Conclusion References

1 2 4 4 5 6 7 8 9 11 11 12 13 15 22 23

2 Introduction to MATLAB Programming 2.1 Introduction 2.2 Basic Features 2.2.1 Features of MATLAB 2.2.2 Uses of MATLAB 2.3 Notation, Syntax, and Operations 2.3.1 Practical Examples for MATLAB 2.3.2 Use of Semicolon (;) in MATLAB

25 26 27 27 27 27 27 28

v

vi

Contents

2.4

2.5

2.6

2.7 2.8 2.9 2.10 2.11 2.12

2.13

2.14

2.3.3 Adding Comments 2.3.4 Commonly Utilized Operators and Special Characters 2.3.5 Unique Variables and Constants 2.3.6 Sparing Process 2.3.7 MATLAB Decisions 2.3.8 MATLAB Loops Import and Export Operations 2.4.1 Import Data in MATLAB 2.4.2 Export Data in MATLAB Elements 2.5.1 Commands 2.5.2 MATLAB Basics 2.5.3 Creating Matrices 2.5.4 Framework Operations 2.5.5 Using M-Files Plotting 2.6.1 Including Various Types of Graphs 2.6.2 Creation of a Multiple Number of Functions in a Similar Graph 2.6.3 Creating a Graph According to Various Colors Uncommon Function Executable Files Generation Calling and Accumulating Executable Documents Calling Objects from External Programs JAVA Classes The Guide 2.12.1 Open a New User Interface 2.12.2 Guide Window Size Setting 2.12.3 Design the User Interface 2.12.4 Adjust the Components 2.12.5 Mark the Push Buttons 2.12.6 Menu Items-Rundown Pop-Up 2.12.7 Static Test Alteration Procedure in MATLAB 2.12.8 Spare the Layout 2.12.9 Behavior of the App 2.12.10 Produce Data to Plot in MATLAB 2.12.11 Pop-Up Menu Characteristics 2.12.12 Behavior of Push Button Effective Programming through MATLAB 2.13.1 Condition 2.13.2 Practice Programs 2.13.3 Specific Functions in MATLAB Clones Process Using MATLAB 2.14.1 GNU Octave 2.14.2 Scilab 2.14.3 Sage

29 29 30 30 30 31 32 32 38 40 40 41 42 42 44 47 48 49 50 51 52 54 55 56 56 57 58 58 59 60 61 61 62 63 63 65 66 67 68 68 69 69 69 70 70

Contents vii 2.15 Parallel MATLAB System 2.15.1 Run a Batch Job 2.15.2 Run a Batch Parallel Loop 2.15.3 Current Folder Browser - Run Script as Batch Job 2.16 Conclusion References

71 71 72 73 74 75

3 Digital Communication System Simulation Using MATLAB 3.1 Introduction to Digital Communication 3.1.1 Data Transmission 3.1.2 Example 3.1.3 The Conversion of Analog and Digital Signals 3.1.4 Information, Bandwidth, and Noise 3.2 Simulation of Rayleigh Fading Model 3.2.1 Rayleigh Fading Basics 3.2.2 Rayleigh Fading 3.3 BPSK Modulation and Demodulation 3.3.1 BPSK Modulation 3.3.2 BPSK Demodulation 3.4 QPSK Modulation and Demodulation 3.4.1 QPSK Transmitter 3.4.2 QPSK Receiver 3.4.3 Performance Simulation over AWGN 3.5 Image Error Rate vs Signal-to-Noise Ratio 3.5.1 M-QAM Modulation 3.5.2 Baseband Rectangular M-QAM Modulator 3.6 Recreation of OFDM Framework 3.6.1 Figuring (Es /N0 ) or (Eb /N0 ) for OFDM Framework 3.6.2 Impact of Cyclic Prefix on Es /N 3.6.3 Effect of Unused Subcarriers on Es/N 3.6.4 Arrangement of Subcarriers 3.6.5 MATLAB Sample Code 3.7 Conclusion References

77 78 78 79 80 82 83 83 84 86 86 87 89 90 93 93 94 94 95 99 101 101 102 103 103 108 109

4 Statistical Analysis of Network Data Using MATLAB 4.1 Introduction to Association Networks 4.2 Time Series, Stationary, Time Series Decomposition, De-trending 4.2.1 Time Series Analysis 4.2.2 Stationarity 4.2.3 Time Series Decomposition 4.2.4 De-trending 4.3 Autocorrelation, Test for Independence, Linear Autoregressive Models 4.3.1 Autocorrelation 4.3.2 ACF and IACF Parameters 4.3.3 Test of Independence

111 112 114 114 115 117 118 124 124 126 128

viii

Contents 4.3.4 Linear Autoregressive Models 4.3.5 Linear Prediction and Autoregressive Modeling 4.4 Mutual Information and Test for Independence 4.4.1 Testing the Significance of the Null Hypothesis I(X; Y ) = 0 4.4.2 Producing the Mutual Information Distribution from Surrogates 4.5 Spurious Cross-Correlation, Vector Autoregressive Models and Dynamic Regression Models 4.5.1 Cross Correlation 4.5.2 Vector Autoregression (VAR) Models 4.5.3 Coupled Dynamical Systems 4.6 Conclusion References

135 137 139 139 141 143 143 146 149 150 150

5 Network Routing Simulation Using MATLAB 5.1 Evaluation of Granger Causality Measures on Known Systems 5.1.1 A Historical Viewpoint 5.1.2 Application to Recreated Information 5.1.3 Application to FMRI BOLD Information from a Visuospatial Consideration Undertaking 5.2 Demand Modeling and Performance Measurement 5.2.1 Objectives 5.2.2 Approach to Model Development 5.2.3 Development of Models 5.2.4 Outline of Findings from Phase Two: Model Validation 5.3 Universal Algorithms and Sequential Algorithms 5.3.1 Genetic Algorithm for Improvement Utilizing MATLAB 5.3.2 Masses Diversity-Measure-Run, Prosperity Scaling 5.4 Acoustic-Centric and Radio-Centric Algorithms 5.5 AODV Routing Protocol 5.5.1 Keeping Up Sequence Numbers 5.5.2 Association Breaks 5.5.3 Neighborhood Repairs 5.5.4 Security Considerations 5.6 Conclusion References

155 156 158 164

6 Wireless Network Simulation Using MATLAB 6.1 Radio Propagation for Shadowing Methods 6.1.1 Radio Propagation Modeling 6.1.2 Partition Dependence 6.1.3 Small-Scale Blurring 6.1.4 Free-Space Propagation 6.1.5 Ray Tracing 6.1.6 Indoor Propagation 6.1.7 Classic Empirical Models 6.1.8 COST 231-Hata Model 6.1.9 COST 231-Walfish-Ikegami Model

209 210 210 210 210 211 212 220 221 221 222

170 173 173 174 175 176 178 178 182 190 194 196 196 197 197 203 204

Contents ix 6.1.10 Erceg Model 6.1.11 Multiple Slope Models 6.2 Mobility: Arbitrary Waypoint Demonstrates 6.2.1 Random Waypoint Model 6.2.2 Regular Problems with Random Waypoint Model 6.2.3 Irregular Waypoint on the Border (RWPB) 6.2.4 Markovian Waypoint Model 6.3 PHY: SNR-Based Bundle Catches, Communication, Dynamic Transmission Rate and Power 6.3.1 MAC: IEEE 802.11 6.3.2 IEEE 802.11 RTS/CTS Exchange 6.4 NET: Ad Hoc Routing 6.4.1 Dynamic Destination Sequenced Distance Vector 6.4.2 Wireless Routing Protocol 6.4.3 Global State Routing 6.4.4 Fisheye State Routing 6.4.5 Hierarchical State Routing 6.4.6 Zone-Based Hierarchical Link State Routing Protocol 6.4.7 Clusterhead Gateway Switch Routing Protocol 6.4.8 Cluster-Based Routing Protocols 6.4.9 Ad Hoc On-Demand Distance Vector Routing 6.4.10 Dynamic Source Routing Protocol 6.4.11 Temporally Ordered Routing Algorithm 6.4.12 Associativity-based Routing 6.4.13 Signal Stability Routing 6.5 APP: Overlay Routing Protocols 6.5.1 System/Application Designs, Optimizations, and Implementations on Overlay Networks 6.5.2 Routing Overlays for VoIP 6.5.3 Measurement, Modeling, and Improvement of BitTorrent Overlays 6.6 Conclusion References 7 Mobility Modeling for Vehicular Communication Networks Using MATLAB 7.1 Vehicle Network Toolbox 7.1.1 Transmit and Receive CAN Messages 7.1.2 Examine Received Messages 7.1.3 CAN Message Reception Callback Function 7.2 Network Management (NM) 7.2.1 Plan Your Network Installation 7.2.2 Planning Your Network Installation 7.2.3 Setting Up a Remote Client Access Configuration 7.2.4 Setting Up Local Client Access Configuration 7.3 Interaction Layer 7.3.1 Directing Protocols in MANET 7.3.2 Specially Appointed On-Demand Distance Vector

224 225 234 234 235 235 235 235 236 237 238 240 243 243 244 244 245 246 247 248 249 250 252 253 254 254 255 256 259 260 267 268 268 271 272 274 274 275 275 275 277 278 278

x

Contents 7.3.3 Dynamic Source Routing (DSR) 7.3.4 Diagram of Mobility Model 7.3.5 Results and Analysis 7.3.6 Association Variation Results 7.4 Transport Protocols 7.4.1 TCP Transport Protocol 7.4.2 User Datagram Protocol, or UDP 7.4.3 Reliable Data Protocol, or RDP 7.4.4 Transmission Control Protocol, or TCP 7.5 Conclusion References

8 Case Studies and Sample Codes 8.1 Case Determination and Structure 8.1.1 Exhibiting Analysis 8.1.2 Case Example 8.1.3 The Best Strategy 8.1.4 Impediment of the Technique 8.1.5 Sorts of Contextual Investigations 8.1.6 Relevant Examinations in Business 8.1.7 Summing Up from Logical Investigations 8.1.8 History 8.1.9 Related Vocations 8.2 Case Study 1: Gas Online 8.2.1 Load Data into Project 8.2.2 Construct Boundary Models 8.3 Case Study 2 8.3.1 Case 1: Create a Credit Scorecard Dissent 8.3.2 Case 2: Binning Information 8.4 Case Study 3: Random Waypoint Mobility Model 8.5 Case Study 4: Node localization in Wireless Sensor Network 8.6 Case Study 5: LEACH Routing Protocol for a WSN 8.7 Conclusion References

278 279 280 282 285 285 286 286 286 287 288 291 292 293 293 293 293 294 294 294 295 295 296 296 296 302 302 304 306 312 325 334 334

List of Figures 1.1 1.2 1.3 1.4 1.5 1.6 1.7 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13

System modeling and simulation scheme. Network simulator abstraction. Discrete-event simulation. Principles of discrete-event simulation and the system state changes only at discrete point’s ti in time during the simulation. Flow chart explaining a discrete-event test system. Wireless sensor network model. Tier-based node model. MathWorks MATLAB R2018b MATLAB decision. MATLAB loops. MATLAB elements. Create an M-File. How to add new toolbox to MATLAB. Initializing deploy tool in MATLAB. Initializing standalone application. Initilazing toolboxes required. Inspecting MATLAB GUI. Simple GUI. Selecting callback options. Selecting callback options 2. Running script as batch job. Data transmission system. Time domain and frequency domain representation of a signal. Analog-to-digital conversion. Upper panel: Periodic sampling of an analog signal. Bottom panel: Quantization of a sampled signal. Simulation results. BPSK modulator. BPSK demodulator. Sampling and results. Waveform simulation model for QPSK modulation. Timing diagram for BPSK and QPSK modulations. Waveform simulation model for QPSK demodulation. Simulated QPSK waveforms at the transmitter side. M-QAM modulator.

5 6 7 8 10 13 14 26 30 31 41 45 47 53 53 54 63 65 65 67 74 78 79 81 81 85 86 87 89 90 92 93 94 95 xi

xii 3.14 3.15 3.16 3.17 3.18 3.19 3.20 3.21 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14

List of Figures M-QAM simulation model. Samples of in-phase component. An OFDM communication architecture with a cyclic prefix. Effect of cyclic prefix on Es /N0 . Assignment of OFDM subcarriers. Eb /N0 Vs BER for BPSKOFDM over AWGN. OFDM essential Tx-Rx chain. 108 BER results. Flowchart of association rules implementation. (a) ARN for contact lens data with target node as hard; (b) ARN for contact lens data with target node as soft. Schematic diagram showing the activity method of communication in a software with ARN. Time series plot for adjusted AUTOSALE/CPI. Time series chart with obtained output form. Output of wave configeration. Error rates identification. Density estimate for power spectral. Density estimate for periodogram spectral. Plottings of the estimate. Markov plottings. Parameters of new functions. Replot status. VAR models. Each middle purpose of the structure is related to a signal. Edges between focus remain for reliance (shared data) between the signs. Basic driving cases that can incite fake unmistakable check of huge Granger causality. Granger causality patterns between simulated ROIs. Comparison of model estimation by LASSO-GC and pairwise GC. Correlation of LASSO-GC and pairwise-GC techniques in recouping the summary measurement. Correlation of LASSO-GC and pairwise-GC techniques in recuperating the W summary measurement. Examination of network designs with LASSO-GC and connection measures. Utilitarian availability examination of dorsal attention network and visual occipital cortex in visualspatial consideration. Different phases of approach in attributes. GAs in MATLAB’s Optimization Toolbox. Rastrigin’s function optimization with the default setting. Rastrigin’s function optimization with the default setting, except Stopping Criteria-Stall Generations set 100 and initial range set [1; 1.1]. Rastrigin’s function optimization with the default setting, except Stopping Criteria-Stall Generations set 100 and initial range set [1; 1.1]. Rastrigin’s function optimization with the default setting, except Stopping Criteria-Stall Generations set 100 and initial range set [1; 2].

96 98 99 101 103 107 108 112 113 113 116 117 125 130 137 138 140 142 144 145 146 156 162 166 167 169 170 171 173 177 180 181 182 183 183

List of Figures 5.15 5.16 5.17 5.18 5.19 5.20 5.21 5.22 6.1

6.2 6.3

6.4 6.5 6.6 6.7

6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16 6.17 6.18 6.19 6.20 6.21 6.22 6.23 6.24 6.25 6.26

Lower raw fitness value. Higher raw fitness value. Stochastic uniform selection method. Elite count 10. Elite count 3. Elite count 1. Estimation of frequency relation to error over time. Radiation readings for distributed beamforming. Spherical free-space propagation: power transmitted over the air radiates spherically, with different gain in different directions. A portion of that power is received on an active aperture area Ae of the receiving antenna. Ray model geometry. Simple propagation models: free-space one-slope direct line of sight, and two-ray with direct ray and ground reflected ray. In some places, signal adds constructively, in others phase differences cause deep fades. Vertical polarization ground reflection coefficient. Horizontal polarization ground reflection coefficient. Six-ray model (R0;R1;R2) and ten-ray model (R0 to R4) geometry: each line hides two rays, one direct, the other bouncing off the ground. Ray tracing plots of received signal power indicator 20log|Σi=N i=0 pi| as a function of log d0 for N {0, 2, 3, 5} for a typical suburban case with street width of 20 feet, and the average distance from the street to the home of wt = 10 feet (so ws = 40 feet). Ray-tracing geometry for a street corridor; some rays escape the corridor through gaps between homes. Ray-tracing power levels down a street, with gaps between homes. 219 Beam following impinging on home dividers. Angles of incidence illuminating homes in an urban corridor. Demonstration of street orientation angle φ for use in COST 231 WalfishIkegami model. Tree foliage attenuation as a function of frequency. COST-231 indoor penetration loss model. Penetration odd into private structures, total thickness dispersion. In-building loss for residential buildings: measurement campaigns published for different frequencies, in different residential areas. In-building loss for urban office buildings and high-rises: measurement campaigns published for different frequencies, in different urban areas. Random waypoint model. MAC layers in IEEE 802.11 standard. RTS/CTS mechanism. Ad hoc routing protocols. Example of distance vector routing. Accuracy of information in FSR. An example of clustering in HSR. Example of CGSR routing from node 1 to node 12. Example of CBRP protocol.

xiii 184 185 185 186 186 187 193 194

211 213

214 215 216 217

218 218 219 220 223 226 230 231 232 232 234 236 237 239 240 244 245 246 247

xiv 6.27 6.28 6.29 6.30 6.31 6.32 6.33 6.34 6.35 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11 7.12 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12 8.13 8.14 8.15

List of Figures Route discovery in AODV. Creation of record route in DSRP. Example of route creation in TORA. Re-establishing route on failure of link 5-7. The new reference level is node 5. Associativity-based routing. An illustrative example of overlay networks. A sample overlay network. Overlay network broken up into logical layers. Overlay network over the Internet. Timestamp identification. Execute the callback function. Remote client access configuration setup. Local client access configuration setup. PDR vs Node Mobility. Packet Loss Rate vs Node Mobility. Routing Overhead vs Node Mobility. Average End-to-End Delay vs Node Mobility. Packet Delivery Ratio vs Number of Connections. Routing Overhead vs Number of Connections. Packet Loss Rate vs Number of Connections. Average End-to-End Delay vs Number of Connections. Two-stage model of torque against spark. ResStatus plot. CustIncome plot. CustIncome plot. TmAtAddress plot. ResStatus plot. EmpStatus plot. Random waypoint mobility model. The location of target and anchor nodes in WSN. (a) Simulated path loss model; (b) Histogram of simulated RSS noise modeled as Gaussian mixture. RMSE vs N (number of anchors). CDF vs error. Cluster formation in LEACH. Steady-state phase in LEACH. LEACH simulation.

248 249 251 251 252 255 257 257 258 271 273 275 276 280 281 281 282 282 283 283 284 301 303 304 305 305 305 306 306 313 324 324 325 325 327 333

List of Tables 1.1 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 4.1 4.2 4.3 5.1 5.2 5.3 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 7.1

Summary of the most important network simulators. Operators and special characters. Unique variables and constants. Variables and constants. Articulations. Loop control statements. Low-level file I/O functions. Framework operations. Setting colors. Calling objects functions. Java class functions. MeansRT and error rates under each condition. Relations between different networks and test sessions. Techniques related to VARM. The fraction of non-zero coefficients in each of the 4 submatrices. 165 Methodologies related to operations. Filtering mechanisms for different models in structural problems. 191 Relative permittivity. Values for COST 231 Hata and modified Hata models. Values of a(hM ) for COST 231 Hata model according to city size. 221 Values of CM for COST 231 Hata model according to city size. Values for COST 231 Walfish-Ikegami model. Values for Erceg model. Values for Erceg model parameters in various terrain categories. Vegetation loss caused by tree foliage reported for various frequencies: single-tree model loss in dB, and dB/m loss. TGn channel models A to F are used to model MIMO systems in a different environment, with different RMS delay spreads. TGn channel models A to F use two slopes n1 = 2 near transmitter and different values of n2 beyond a critical distance d0 . 228 Building penetration loss from COST-231 model. Private structures penetration loss: middle odd (μi ) and standard deviation (σi ) from exploratory outcomes announced for different frequencies. Penetration loss into vehicles: median loss (μv ) and standard deviation (σv ) from experimental results reported at various frequencies. Parameter values in simulation.

15 29 30 31 32 32 35 42 50 55 56 131 132 147 189 216 221 222 223 224 224 226 228

230 231 233 279 xv

Foreword In addition to modeling and simulating systems, this book provides a better understanding of how real-world systems function. This enables us to predict the behavior of systems before they are actually built and to accurately analyze them under various operating conditions. This book provides comprehensive, state-of-the-art coverage of all the essential aspects of modeling and simulation both physical and conceptual systems. Various real-life examples are included, which show how simulation plays a crucial role in understanding real-world systems. We also explain how to effectively use MATLAB to apply the modeling and simulation techniques presented successfully. After introducing the underlying philosophy of the systems, the book offers step-bystep procedures for modeling with practical examples, and codes different types of systems using modeling techniques such as the Rayleigh fading model, BPSK modulation and demodulation, QPSK modulation and demodulation, etc. This book will prepare both undergraduate and graduate students for advanced modeling and simulation courses, and will help them carry out useful simulation studies. Moreover, postgraduate students should be able to comprehend and conduct simulation research after completing this book.

xvii

Preface This book is organized into eight chapters. In Chapter 1 a detailed overview is provided on how MATLAB can be used for network simulation and modeling. Then various types of simulation are described, followed by their working principles and different terminologies, along with the algorithms governing these simulations. The chapter also describes the selection of various software simulations for MATLAB, and the simulation tools based on high performance, followed by the different network models. This chapter will effectively help readers understand the concepts more clearly and provide them with a clear understanding of how to perform these tasks in MATLAB. In Chapter 2, the power of MATLAB for computational mathematics is shown, followed by a detailed description of the features. A detailed discussion of various areas of MATLAB use is provided. We also discuss multiple notations, operators, and syntax and give hands-on practical examples along with various loop structures and decision controls, import, and export operations, using and creating M-files, different types of plotting and graphs, etc. Also explained are the various clones of MATLAB. This chapter will effectively help readers understand the workings and uses as well as applications of MATLAB more clearly. In Chapter 3, we explain how digital communication system simulations can be performed using MATLAB. A detailed introduction to digital communications, i.e, data transmission, is provided along with an example. Next, a detailed explanation of simulations of Rayleigh fading model, BPSK modulation and demodulation, QPSK (Quadrature Phase Shift Keying) modulation and demodulation is given, along with their MATLAB coding, and the output is shown as well. We image error rate vs signal-to-noise ratio and OFDM with sample MATLAB coding and their output. In Chapter 4, we explain how to perform statistical analysis of network data utilizing MATLAB starting from affiliation systems/networks with examples. Time series analysis, statistical stationarity, time series decomposition, de-trending, curve fitting, digital filtering, recurrence reaction, and the connection between recurrence reaction to spline parameter are also explained. Next, details are provided about autocorrelation, test for independence, linear autoregressive models, etc. In Chapter 5, we explain how network routing simulations can be done using MATLAB. Additionally, deep insights are provided about the evaluation of Granger causality measures on known systems, along with results. We explain the application to fMRI BOLD (BloodOxygenation-Level-Dependent) information from a visuospatial consideration undertaking followed by various model development approaches, models validation, universal algorithms, and sequential algorithms, acoustic-centric and radio-centric algorithms, AODV routing protocols, etc.

xix

xx

Preface

In Chapter 6, we explain how wireless network simulations can be done using MATLAB. We explain how shadowing methods are used for radio propagation, two-ray model, indoor propagation, classical empirical model, Hata model, Walfisch-Ikegami model, Erceg model, multi-slope model, dispersive model, 3GPP SCM, MAC: IEEE 802.11 (CSMA/CA, virtual carrier sense, and RTS-CTS-DATA-ACK), NET-ad hoc routing, APP-overlay routing protocols, etc. In Chapter 7, we explain various layers and protocols such as Vehicle Network Toolbox. In this toolbox, an explanation is given on how to make a receiving channel, how to access a chain, how to start a channel, how to transmit a message, etc. Next, the topic of network management (NM) is presented, in which a detailed explanation is given of network installation planning, setting up a remote client access configuration, interaction layer, directing protocols in MANET, along with their results and analysis, and transport layer with protocols. In Chapter 8, a detailed explanation is provided of various real-time scenarios by using case studies taken from multiple real-time situations with their sample codes and result from analysis for a better understanding of how MATLAB performed in these situations and how it can solve critical simulation problems in detail. Dr. Dac-Nhuong Le Deputy-Head, Faculty of Information Technology Haiphong University, Haiphong, Vietnam Abhishek K. Pandey Assistant Professor (Computer Science Engineering) ACERC, Visiting faculty, Mdsu, Ajmer Rajasthan, India Sairam Tadepalli Junior Data Scientist, AWS Architect, Python Developer Pramod Singh Rathore Assistant Professor (Computer Science Engineering) ACERC, Visiting faculty, Mdsu Ajmer Rajasthan, India Jyotir Moy Chatterjee Assistant Professor (IT) Lord Buddha Education Foundation (APUTI), Kathmandu, Nepal

Acknowledgments First of all, I would like to thank the authors for contributing their chapters to this book. Without their contributions, this book would not have been possible. Thanks to all my associates for sharing my happiness at the start of this project and following up with their encouragement when it seemed to be too difficult to complete. I want to acknowledge and thank the most important people in my life, my grandfather, grandmother, and finally thanks to my wife. This book has been a long-cherished dream of mine which would not have been turned into reality without the support and love of these fantastic people, who encouraged me despite my not giving them the proper time and attention. I am also grateful to my best associates for their blessings and unconditional love, patience, and encouragement. Dac-Nhuong Le Deputy-Head, Faculty of Information Technology Haiphong University, Haiphong, Vietnam Writing a book is harder than I thought and more rewarding than I could have ever imagined. First and foremost, I would like to thank my father Mr. Krishan Dev Pandey for being the coolest father ever and my mother Mrs. Veena Pandey for allowing me to follow my ambitions throughout my childhood. They taught me discipline, tough love, manners, respect, and so much more that has helped me succeed in life. Also, I would like to express my gratitude to my elder sister Mrs. Arpna Tripathi, who always stood by me during every struggle and all my successes. She has been my inspiration and motivation for continuing to improve my knowledge and move my career forward. Also, I’m eternally grateful to my wife, Mrs. Kajal Pandey, for standing beside me throughout my career and the writing of this book. I also thank my wonderful son, Aarudra Pandey, for always making me smile and for understanding on those weekend mornings when I was writing this book instead of playing games with him. I hope that one day he can read it and understand why I spent so much time in front of my computer. Last but not the least, I want to thank my friends who always backed me up during both good and bad days and everyone who ever said anything positive to me or taught me something. I heard it all, and it meant something. Abhishek K. Pandey Assistant Professor (Computer Science Engineering) ACERC, Visiting faculty, Mdsu, Ajmer Rajasthan, India.

xxi

Acronyms AAL ABR ACK AODV ASK ANT ASW ARIMA AR AS ASAP B.A.T.M.A.N BPSK BOLD CDF CSMA/CA CSMA/CD CLPC CTS CRLB CBRP CGSR DSR DAN DREAM DSSS DSDV DSRP DRP DHT ECG EEG FMRI FEF FHSS FFT

Ambient Assistive Learning Associativity Based Routing Acknowledgement Ad hoc On-Demand Distance Vector Amplitude-Shift Keying Attention Network Test Apparent Source Width Autoregressive Integrated-Moving-Average Auto Regressive Autonomous System AS-Aware Peer-relay Protocol Better Approach To Mobile Adhoc Networking Double Phase Shift Keying Blood-Oxygenation-Level-Dependent Cumulative Distribution Function Carrier-Sense Multiple Access with Collision Avoidance Carrier Sense Multiple Access with Collision Detect Cross-Layer setup approach for Power Control Clear to Send Cramer-Rao Lower Bound Cluster based Routing Protocol Clusterhead Gateway Switch Routing Dynamic Source Routing Dorsal Attention Network Distance Routing Effect Algorithm for Mobility Direct Sequence Spread Spectrum Destination-Sequenced Distance-Vector Routing Dynamic Source Routing Protocol Dynamic Routing Protocol Distributed Hash Table Electrocardiogram Electroencephalogram Functional Magnetic Resonance Imaging Frontal Eye Field Frequency Hopping Spread Spectrum Fast Fourier Transform xxiii

xxiv

Acronyms

FSR GC GA GM-SDP GUI GSR IACF IEEE ITU-T JiST LASSO LEACH LOS LCC LUT M-QAM MWP MANET MVAR MIMO MWP MRL MUEL NM NS NHST NLOS OFDM OLSR OS OMNET PAN PHY P2P PLL PSK PROWLER QPSK QAM RWPB RWP RWPB RERR RREP RPGM RDP

Fisheye State Routing Granger Causality Genetic Algorithm Gaussian Mixture-SemiDefinite Programming Graphical User Interface Global State Routing Interaural Cross correlation Function Institute of Electrical and Electronics Engineers International Telecommunication Union-Telecommunication Java in Simulation Time Least Absolute Shrinkage and Selection Operator Low Energy Adaptive Clustering Hierarchy Line of Sight Least Cluster Change Look-Up-Table M-ary Quadrature Amplitude Modulation Markovian Waypoint Model Mobile Ad-hoc Network Multivariate Vector Auto Regressive Multiple In, Multiple Out Markovian Waypoint Model Message Retransmission List Minimize Usage Extend Life Network Management Network Simulator Null Hypothesis Significance Testing Non Line of Sight Orthogonal Frequency Division Modulation Optimized Link State Routing Protocol Operating System Object-Oriented Modular Discrete Event Simulator Personal Area Network Physical Layer Peer-to-Peer Phase Locked Loop Phase-Shift Keying Probabilistic Wireless Network Simulator Quadrature Phase Shift Keying Quadrature Amplitude Modulation Irregular Waypoint on the Border Arbitrary Waypoint Discretionary Waypoint on the Periphery Route Error Route Reply Reference Point Group Mobility Model Reliable Data Protocol

Acronyms xxv ROI RON RTS RREQ RT RFC RSS RMSE SSR SSF SNAP SST SRP SCM SDP SNR SwaP SWANS TORA TCP TCP/IP TTL TOSSIM TDMA UDP VAR VANET VOC VPN VoIP ZRP ZHLS WRP WLS WSN WOE WIMAX 3GPP

Region of Interest Solid Overlay Networks Request to Send Route Request Response Time Request for Comments Received Signal Strength Root Mean Square Error Signal Stability Routing Scalable Simulation Framework Simulation Analysis Platform Signal Stability Table Static Routing Protocol Spatial Channel Model Semidefinite Programming Signal-to-Noise Ratio Weight and Power Scalable Wireless Ad hoc Network Simulator Temporally Ordered Routing Algorithm Transmission Control Protocol Transmission Control Protocol/Internet Protocol Time to Live Tiny Operating System Sensor Network Time Division Multiple Access User Datagram Protocol Vector Autoregression Vehicular Ad hoc Network Visual Occipital Cortex Virtual Private Network Voice over Internet Protocol Zone Routing Protocol Zone-based Hierarchical Link State Routing Protocol Wireless Routing Protocol Weighed Least Square Wireless Sensor Network Weight of Evidence Worldwide Interoperability for Microwave Access 3rd Generation Partnership Project

CHAPTER 1

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

Abstract In this chapter, we have tried to provide a detailed overview of how MATLAB can be used for network simulation and modeling. We describe simulation and its various types, followed by their working principles and different terminologies, and the algorithms governing these simulations. Also described are various simulation software selections for MATLAB, the simulation tools based on high performance, followed by the different network models. This chapter will effectively help readers understand the concepts more clearly and provide them with a clear understanding of how to perform these tasks in MATLAB. Keywords: MATLAB, modeling, simulations

Network Modeling, Simulation and Analysis in MATLAB. c 2019 Scrivener Publishing By Dac-Nhuong Le et al. Copyright 

1

2

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

1.1

MATLAB Modeling and Simulation

The representation of the system in learning is an abstraction, as mentioned previously. This means that it will not generally be considered with a more significant number of features as well as characteristics of the system and also that it only produces elected features and characteristics. Hence, based on simplifications and assumptions, the received model representation is a compact enactment of the system. Learning the sequence for identifying the appropriate entities and their relationships with the system is known as modeling. Two important questions arise for any researcher when dealing with the evaluation of the performance of the system: Question 1 - What is a good model? Question 2 - How to obtain it? Here it is essential to take care of two additional factors if the evaluation method is represented as the computer simulation. (i) It has to be implemented in software once the performance model is built. Hence, the “model” performance is to be of high quality, as the implementation needs to represent it. (ii) Hence, a suitable tool requirement needs to be selected which formally suits the process of the evaluation method. The modeling for computer simulations of these four cornerstones are combined. Sadly, the problem is that a large number of them are complex, and generally, we need specific prior learning experience with modeling and simulation. “Essentially, all models aren’t right, yet some are helpful” is the reality of execution. By remembering this, a great execution (either for investigation or for reenactment) has the following qualities: Simplicity: It is conceivable that the execution models are great. This does not imply that an execution model ought not be point by point or ought not to attempt to consider complex connections. In any case, a great execution displays its multifaceted nature when it fills the need of the assessment (additionally alluded to as objective of the investigation). Because of the shortage of exactness in contrast with the real world, this is a fundamental point in reproduction models which are regularly scrutinized. This is basically the notion od computer simulation and manufactured the rganized nodes so that mixing of nodes can be minimized to get better accuracy. For the reusability of execution models, it has certain additional results. Usually, the assessment contemplates have different objectives (primarily if they will be distributed to established researchers), so there is likely a contrast in the utilized execution models. For systems, it clarifies a large number of open-source reproduction models, and for across-the-board organizing frameworks, it explains the nonattendance of prevailing or standard reenactment models to a certain degree. To fill all needs, there

MATLAB MODELING AND SIMULATION

3

is no reenactment shown. Any recreation demonstrate which is accessible has been planned given a specific assessment target. One should first check the first assessment reason which is served by the model, and it needs to reuse the particular reproduction display. Reliability: The basic part of execution models is their stable quality. The clarification behind the evaluation of modeling has been made clear initially for better efficiency. In the resulting phase of the modeling system, the assumptions and reenactments ought to have been noticed, including its evolution phases. From the learning phases of the model to final output phase, model representation and its simulation plays an important role in finding the reliability of the resultant model. In the simulation part of the modeling, the recreation of the model is very much important for better analysis of the model. The analysis result states that there difference between evaluation procedure and final output and its application model. So reliability factor has to deal with all the above-mentioned analysis. So a genuine programming model can only result in better reliability of the system, as it is reliable for better execution, evaluation and final applications. Notwithstanding the qualities of a decent execution display, a great reproduction model ought to have the accompanying attributes: Proficiency: As for the execution show up, it ought to be finished reasonably after a particular instant of time. In like way, running events of simulation is quick and different analysis results can then be visible. Checked: The executed reenactment model ought to be confirmed, i.e., the similarity between the execution shown and reproduction demonstrate that it more likely than not has been checked by different strategies. Note that this progression is not quite the same as approving an execution or reproduction display. Code Quality: Reliability on reusability of the code can result in using a specific programming method which is responsible for avoiding confusion in system programming and further simulation for achieving the desired results. Accessibility: Reproduction model ought to be available with the end goal that different gatherings confirm and approve the model themselves. As expressed previously, an execution show isn’t required to be as point by point as could reasonably be expected. Truth be told, finding the correct level of exactness for an execution show is very troublesome. A typical oversight in demonstrating is to put excessive detail into a model because of the need for both involvement in execution assessment or foundation information about the framework under investigation. Lastly, a great execution does not need to be all inclusive nor for the most part reusable.

4

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

1.2

Computer Networks Performance Modeling and Simulation

1.2.1

Computer-Based Models

Computer-based models are usually classified as follows [1, 2]: Deterministic vs Stochastic: A deterministic model predicts a specific output from a given set of inputs with neither randomness nor probabilistic components. A given input will always produce the same output given the same initial conditions. In contrast, a stochastic model has some inputs with randomness, hence the model predicts a set of possible outputs weighted by their likelihoods or probabilities. Steady-state vs Dynamic: A steady-state model tries to establish the outputs according to the given set of inputs when the system has reached steady-state equilibrium. In contrast, a dynamic model provides the system reactions facing variable inputs. Steady-state approaches are often used to provide a simplified preliminary model. Discrete vs. Continuous values: A discrete model is represented by a finite codomain, hence the state variables take their values from a countable set of values. In contrast, a continuous model corresponds to an infinite codomain. Therefore, the state variables can take any value within the range of two values. However, there are some systems that need to be modeled showing aspects of both approaches which bring about combined discrete-continuous models. Discrete vs Continuous time: In a discrete model the state changes can only occur at a specific instant in time. These instants correspond to significant events that impact the output or internal state of the system. In contrast, in a continuous model the state variables change in a continuous way and not abruptly from one state to another. Therefore, continuous models encompass an infinite number of states. Discrete models are the most commonly used for network modeling and simulation. Simulations can be carried out following two approaches: local and distributed. Distributed simulation is such that multiple systems are interconnected to work together, interacting with each other, to conduct the simulation. In contrast, a local simulation is carried out on a single computer. Historically, the latter approach has been the most widely used to simulate computer networks, but the increasing complexity of simulations is fostering the importance of the former approach. Figure 1.1 summarizes the modeling and simulation process. Behavioral information extracted from a real system is used jointly with system specifications and requirements. Based on these inputs, a system model is built and subsequently validated through simulation. Usually, several performance metrics are determined during simulations, which can be compared with results extracted from experimentations with the real system. If both are similar, the model is considered as valid, while if they are not, the system model must be corrected. Similarly, performance metrics

COMPUTER NETWORKS PERFORMANCE MODELING AND SIMULATION

5

are used to determine if the system model fulfills the requirements, so the designed system can be refined and extended in a controlled way.

Figure 1.1

1.2.2

System modeling and simulation scheme.

Computer Network Simulation

Nowadays, computer network simulation is a fundamental element in network researching, development and teaching. Network simulators are widely used not only by practitioners and researchers, but also by students to improve their understanding of computer networks. Network simulation can be extremely useful when applied to scenarios such as protocol analysis, complex network deployment, evaluation of new services, prototypes or architectures, and so on. Broadly speaking, a network simulator can be understood as a black box, as illustrated in Figure 1.2 [13, 23, 24] A network simulator implements a computer network model through algorithms, procedures and structures according to a given programming language. The implemented network model receives a set of parameters as inputs, which impose the rules and constraints of the simulation. In other words, these parameters set the course of the simulation. When the simulation process ends, the network simulator returns a set of results as outputs that can be used with a dual purpose: validating and veri-

6

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

fying the correctness of the implemented model for a particular domain of system states, and analyzing the behavior of the network modeled when the former has been successful [15-17].

Figure 1.2

Network simulator abstraction.

Computer networks are most often simulated with discrete-event simulation. The main reason behind this widespread use is that discrete-event simulation adapts better to represent the behavior of computer networks, since computer network protocols can be modeled as finite state machines. In a computer network there is a steady state between two consecutive events, and discrete-event simulation allows for jumping from one steady state to another, leading to faster simulations. Other interesting aspects of discrete-event simulation are flexibility and lower computational overhead. 1.3

Discrete-Event Simulation for MATLAB

Discrete event simulation utilizes a mathematical/logical model of a physical system that portrays state changes at precise points in simulated time. Both the nature of the state change and the time at which the change occurs mandate precise description. Customers waiting for service, the management of parts inventory or military combat are typical domains of discrete event simulation [10, 11]. A more theoretical top-down description of discrete-event simulations is the following: The start of a discrete-event simulation is a model. A model is the construction of a conceptual framework, used to represent a system. The specific characteristics of discrete-event simulation model are the following: 1. Stochastic: At least some of the model’s components are stochastic. This means that there is a certain factor of randomness in the model. This is represented by random number generators, which are explained in the terminology. 2. Dynamic: The time evolution of the system’s components is important. Time is a significant variable. 3. Discrete: The state of the system changes only significantly when events occur at discrete time instances.

DISCRETE-EVENT SIMULATION FOR MATLAB

Figure 1.3

7

Discrete-event simulation.

The difference with continuous simulations is the use of the factor time. The system evolves over time so the variables change continuously in a continuous simulation. Whereas in a discrete event simulation the events themselves determine if something happens or not. Time can go by without anything happening. We will give a concise introduction into discrete-occasion reenactment and for this we present the essential phrasing utilized in writing to clarify their connections. Likewise, for a discrete-occasion test system we present the center calculation, i.e., the time-propel occasion booking calculation.

1.3.1

Terminology and Components of Discrete-Event Simulation

Some common phrasing and elements for all discrete-occasion reproduction frameworks are known. In writing the terminology may change and surprisingly there is no institutionalized arrangement of terms. In a portion of our reference papers we freely adjust the definitions. A reflection of a specific subject of intrigue is alluded to as substance and it very well may be depicted by its own properties; For example, an element bundle carries its source (address), qualities, length as well as goal (address). The relationship of a suitable set of entities is defined as a system. A certain purpose can be fulfilled by the relationship of a suitable set of entities, i.e., the system attempts to achieve a certain goal. For example, the goal of a network provides endto-end connectivity while it may be defined by the routers, links and the entities hosts. The model is defined as the system and the use of the following methods refers to an abstracted system and is termed the model for clearness. During the process of minimizing the difficulty and the correlated cost as well as, effort involved, it will always consider the model in computer simulations.

8

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

1.3.2

The Principle of Discrete-Event Simulation

It is possible to utilize the discrete-event test system to bounce from one event to the next, and the rate an occasion might incite can be modified in the state of framework and also the age of a newer, supposed event occurred in future. To deal with every one of the events in the discrete-event simulation, the events are recorded as events seen later on the event list (FEL). To embed, to discover and to evacuate events seen, which are set later on, an event rundown ought to be actualized effectively later on in the event list [25]. Figure 1.4 demonstrates the growth of discrete-event simulation after some time. The events happen at the given time interval ti and might alter the state of framework. To advance the reenactment with each discrete-event time ti , in the PC memory a depiction of the framework is made that contains every required datum.

Figure 1.4 Principles of discrete-event simulation and the system state changes only at discrete point’s ti in time during the simulation.

Typically all discrete-event test systems share the following components: System express: The condition of the framework can be depicted by the arrangement of factors. Entities: Temporary entities are the elements that flow through the system. They wait in queues, follow a sequence of events and are specified by certain attributes. Most entities are introduced in a system according to a stochastic distribution. Examples of temporary entities are: parts of goods, customers and information messages. Permanent entities remain in the system when the simulation is executed. They are used in the events to process the temporary entities. The usage time of permanent entities is mostly stochastically distributed. Examples of permanent entities are: operators, servers and machines. Attributes: Entities own attributes that specify certain properties and states of the entity. They can affect how entities are handled during the sequence of the processes. They are not fixed through the flow so they can change by being processed. Examples of attributes are: priority and quality. Clock: The clock maintains the simulation time. The measurement units vary depending on the characteristics of the model. Because we are dealing with discrete-events, the time is not continuous but “jump” according to the events. The clock is also responsible for the timer of the events.

DISCRETE-EVENT SIMULATION FOR MATLAB

9

Queue: Place where temporary entities wait an undetermined time before being accepted in an event. Some entities might have priority attributes to skip the queue. These queues can, for example, be used to locate overproduction or a bottleneck, as mentioned in the introduction. Random number generators: Most of the previous components need the possibility to generate random variables in order to simulate the stochastic distributions. Pseudorandom number generators are used to accomplish this. Future occasion list: To deal with the events, it very well may be appropriated by the information structure. Statistical counters: The result of a simulation should be shown in the form of a report that gives statistics about all the important components of the discreteevent simulation. These statistics are analyzed to make better decisions. Initialization schedule: To instate the reproduction display we utilize introduction routine and fix the clock value to zero in the framework. Timing schedule: From the future event list a routine recovers the the next occasion and also advances the clock value to the frequency in the framework. Event schedule: Events change the state of the system. A sequence of events can be bundled as an activity. These events determine the timing and the flow of the simulation, hence the word discrete-event simulation. A typical example of an event is the arrival of new entity, often used to start the simulation. The sequence of events ordered by time of occurrence forms an event list. Each simulation has at least one event list. This events list determines the mechanism for advancing the simulation time. This sequence of actions is also called eventscheduling. Every simulation also needs a stopping event or ending condition. This determines how long the simulation will run. Typical stopping events are a specific time in the future or a condition that the simulation itself fulfills. When a specific event happens amid the recreation is called an event schedule. By and large, an event routine is characterized for every event composed. In writing the term handler is frequently utilized synonymously. 1.3.3

ESTA Algorithm

An ESTA algorithm is an event-scheduling/time-advance algorithm [19]. According to their occurrence time, the event notifications are listed inside the future event list, i.e., f el = [t1 , t2 , ..., tk ] where t1 ≤ t2 ≤ ... ≤ tk . (1.1) Here t1 in this case is where an event occurs in time. The diagram in Figure 1.5 below depicts the flow of the ESTA algorithm, which is subdivided into three main sections.

10

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

Figure 1.5

Flow chart explaining a discrete-event test system.

They are: 1. Section 1. Initialization 2. Section 2. Event Processing 3. Section 3. Output Initialization employs three main processes: the first one is the clock, secondly, entities and finally, state variables. After that the simulator enters the second part and the events are processed in a loop. Here a type of specific event has been created, which is termed handler, in which current event is retrieved or recovered from the next events. The state variables, entities and update statistics might be changed by the event routine and new event notices are created. The simulation enters the final part of the process after receiving the valid loop of termination condition. Finally, the statistics are calculated in the output part of the process and will be written into files if necessary.

SIMULATION SOFTWARE SELECTION FOR MATLAB

1.3.4

11

ANALYSIS: Determination of Time to Attain Steady State Condition for MATLAB

By the end of fixed steady time final state will be achieved. You will achieve half of consistent state after one half a life, in the result we will achieve 75 percentage as unfaltering state after two half lives, and in the result we will attain 87.5 percentage enduring state after three half-lives. The enduring state will be attained after five half-lives, which is characterized in the thumb control (97% of consistent state accomplished). By utilizing a stacking dosage, without much effort you can attain the objective of an enduring state in the event that you have a medication with a long half life. For instance, it requires a 30 mg dosage once in multiple days on the off chance that you need to accomplish an unfaltering condition of fixation (Css) of 10 ng/mL. By-and-by, to accomplish an unfaltering state it will take 10 days. Accept that the dosage proportionality, a 60 mg measurement, will accomplish a Css of 20 ng/mL in 10 days, you will attain half an enduring state after a solitary dosage of 60 mg (i.e., 20 ng/mL × half = 10 ng/mL). Subsequently, you can accomplish the relentless state level inside two days and, as previously stated, it could accomplish the objective Css quickly. The stacking measurement is 60 mg and the upkeep dosage is 30 mg. A critical term in pharmacokinetics is “consistent state,” which can appear somewhat theoretical and confounding as well. Another way to think of it is to envision a carton of eggs in your kitchen and you take two eggs out to make an omelet for breakfast and somebody sees that there is a vacant spot in the egg carton and purchases two more eggs to put in the carton. Hence, when you wake up the following morning, there is no empty spot in the carton of eggs and if this procedure repeats and again there is an adjustment made to the number of eggs in the carton, despite the fact that you utilize them for a few days, it will dependably be the same. For this situation you could without much of a stretch comprehend that the rate of end is equivalent to the rate of info and here the eggs are at relentless state.

1.4

Simulation Software Selection for MATLAB

It should be noted that the goal regarding various undertakings in mechanized manufacturing systems is to upgrade productivity and lower cost. To energize plans and review working techniques, the champion among the most typical methodologies is simulation because of the resultant variability and dynamic advantages of such model. Some of the various examinations to be conducted follow. There are certain suggestions made by Banks and Gibson when purchasing the diversion programming such as exactness and detail, incredible capacities, fastest speed, demo game plan of issue and comparing associations with practically identical applications by looking at accumulated social events of customers. Together with their levels of essentialness for the specific reason, a purpose behind the development of propagation packages in the amassing region was presented by

12

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

Hlupic and Paul. While evaluating discrete-event diversion programming, a criteria for the structure should be considered, which was created by Nikoukaran et al [3]. A two-phase evaluation and selection methodology for simulation programming decisions was proposed by Tewoldeberhan et al. [4], in which the feature of propagation packages discussed above was empowered by the connection of two-phase evaluation in organized manner. For apparent improvement of each propagation package different methodologies are used in two-phase propagation evaluation. For discrete-event multiplication, Seila et al. [5] showed a framework to pick the reenactment programming. The proposed framework attempts to recognize the endeavored target first by assessing around 20 programming instruments, since a run-of-the-mill understanding of the objective will help plot charts with internal association resources and also dealer and expert associations. A criterion which can help pros veritably assure business process organization tools was made by Popovi et al. [6]. By including the decision of propagation programming, these examinations are prepared with a more theoretical approach to the issues. This section discusses the programming model, followed by how to use it in the most efficient way, as it gives a couple of optimizing methods like representation of database model and the way the database has to handle the queries. Lastly, essential broadcasting of the analysis right from the inside of Smart Sim Selector can be derived and represented for future enhancement.

1.5

Simulation Tools Based on High Performance

A mobile ad hoc network (MANET) consists of several specific types of networks. One type is a wireless sensor network (WSN), shaped by several sensing devices which employ wireless transmission as the communication medium. It shares the same technical problems which have been noted in the research done on WSNs and MANETs. Two particular factors arise in WSN: usually one of the purposes of sensors is to measure the physical variables which are driven by the protocol layer operations and applications. Hence, the network which governs various types of topologies and traffic load are sensed by the dynamics of physical parameters. In WSN, the primary concern is energy, and frequently the nodes will run on non-rechargeable batteries. Hence, as expected, the lifetime of a node is a fundamental element and must be taken into account. In actuality, in MANETs, vitality is an essential issue that ought to be enhanced, despite the fact that it is for the most part accepted that a hub can energize or supplant its battery. In the interim, sending and working a testbed to examine the real conduct of conventions and system execution is an awesome undertaking [7, 8]. Therefore, recreation is fundamental to contemplate wireless sensor network, since it is the preliminary process in testing newer applications as well as conventions in this field. For this reason, in reality this field has brought about an ongoing surge in reproduction apparatuses accessible to WSNs.

SIMULATION TOOLS BASED ON HIGH PERFORMANCE

13

This scenario contains two key angles which ought to be assessed earlier than directed analysis: Firstly, its accuracy and, secondly, the reasonableness of executing a specific device. On the other hand, an expanding worry regarding strategy as well as presumptions regarding simulations have been presented by Aktar et al. [9] as follows: Admired equipment and conventions can prompt outcomes with mixed results. A “decent” model in view of strong presumptions is compulsory to infer trusted outcomes. In any case, including the required level of detail includes solid computational prerequisites. The essential trade-off is: Exactness and need for detail versus execution and adaptability. A device that constructs a model is required, and the client faces the task of choosing the fitting one. Reproduction programming normally gives a structure to demonstrate and recreate the conduct of genuine frameworks. 1.5.1

Network Model

Figure 1.6 shows a model of a wireless sensor network that depicts the general structure of the network which occurs on a wide scale [18].

Figure 1.6

Wireless sensor network model.

The component descriptions are given below: 1. Nodes: Defined as a set of physical variables monitored by a physical device; each node refers to a physical device. Nodes can communicate with each other through a common radio channel. To control communications internally, a protocol stack is used. A sensor model is not similar to classical network models and it includes secondary components which involve the concept of physical node tier. In additional to it, a “topology” component may control node coordinates, which is not shown in Figure 1.6. 2. Environment: Additionally, an “environment” component is the major dissimilarity from the classical and wireless sensor network models. The nodes which are sensed by this component model trigger sensor actions along with the creation and growth of events, i.e., in the network, communication occurs between nodes.

14

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

3. Radio channel model: In the network, nodes signal propagation and can be characterized by the radio channel model. In ratio model, terrain components are used to calculate the growth of the radio channel. 4. Sink nodes of wireless sensor network model: Sink nodes are known as the special nodes in the network which receive the data present and process it. A note of interest is that they might be integrated in sensors to interrogate the sensors. Testing is performed by the simulator and the sink node used depends on the application. 5. Agents: Agents act as an event generator among the nodes which are present in the network. In the propagation through the environment and the sensor stimulation, the agent is also used to modify the physical magnitude. Because of cross-layer interdependencies, node conduct relies upon collaborating factors. As shown in Figure 1.7, nodes are advantageous for partitioning a hub into theoretical levels.

Figure 1.7

Tier-based node model.

All the correspondence conventions are included in the protocol level. There are three layers which coincide with this level; for example, a directing layer, a MAC layer, and a particular application layer. In this way, in order to trade level data, a productive strategy must be created. The physical-hub level speaks to the equipment stage and its impacts on the execution of the instrument. An arrangement of physical sensors – the vitality module and the portability module – are known as normal components of this level. Physical sensors take the lead in checking equipment. An urgent issue of WSNs takes place at the equipment stage, where the vitality module mimics utilization management. Sensor position is controlled by the versatility module. A hub is associated through two conditions:

SIMULATION TOOLS BASED ON HIGH PERFORMANCE

15

– Condition 1 - Associated through a radio channel – Condition 2 - Associated through at least a physical channel. 1.5.2

Network Simulators

Some of tools of wireless sensor network are network simulators, while others are emulators. A network simulator is a tool used to evaluate network protocol performance in a wireless sensor network, it simulates the network. Some simulators that are discussed here are NS-2, Sensor Sim, SENS, and Em Star [12, 14, 20-22]. Table 1.1

Summary of the most important network simulators.

16

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

A network emulator is a tool used to evaluate real hardware performance on the nodes of a wireless sensor network. Some emulators that are discussed here are TOSSIM, ATEMU and AVRORA. Each of these classes and tools has its specific advantages and disadvantages and often the selection of the tool is mainly based on the experience of the researcher rather than on rational arguments. An overview of the different tools and simulation environments with their particular pros and cons has been established by the CRUISE project.The most relevant simulation environments used to study WSN are introduced and their main features and implementation issues are also described. 1.5.2.1

Network Simulator-2

Network Simulator-2 (NS-2)1 is a discrete event simulator that was designed especially to simulate transmission control protocol (TCP) on wireless and wired networks and it was developed in C++. NS-2 is one of the most popular non-specific network simulators, and supports a wide range of protocols in all layers. It uses OTCL as configuration and script interface. NS-2 is the paradigm of reusability. It provides the most complete support of communication protocol models, among noncommercial packages. Regarding WSN, NS-2 includes Ad-Hoc and WSN specific protocols such as directed diffusion or SMAC. NS-2 can comfortably model wired network topologies up to 1,000 nodes or above with some optimizations. The drawbacks of NS-2 is that the learning curve to operate the simulator is considerable, and knowledge of a scripting language, queuing theory, and modeling techniques is required; also, because the protocols are written in the object-oriented language C++, the simulator does not scale well for simulations of large wireless sensor node networks, as each node is represented as an object and performance is significantly affected. Another disadvantage of NS-2 is that it provides poor graphical support, via Nam. This application just reproduces a NS-2 trace. NS-2 has been an essential testing tool for network research and, so, one could expect that the new conventional protocols will be added to future releases. 1.5.2.2

AVRORA

AVRORA2 is another WSN simulator that simulates a sensor system at a very finely granular level; it was developed by Ben Titzer et al. [12] at UCLA. AVRORA attempts to achieve the advantages of TOSSIM and ATEMU, and mitigate these two emulator’s disadvantages. While TOSSIM and ATEMU are written in the programming language C, AVRORA is written in Java. AVRORA emulates the node operation by running code instruction-by-instruction. The unique feature of AVRORA is how it handles the synchronization of nodes. There are two modes of synchronization: one uses a regular interval that can be set by the emulation operator to synchronize nodes; the other mode allows nodes to proceed along in simulation, until it reaches a state where it has to synchronize with its neighbors. Both of these synchronization modes reduce the overhead introduced by the synchronization function, as compared to TOSSIM and ATEMU. 1 https://www.isi.edu/nsnam/ns/ 2 compilers.cs.ucla.edu/avrora/

SIMULATION TOOLS BASED ON HIGH PERFORMANCE

1.5.2.3

17

OMNET++

OMNET++ (Object-oriented modular discrete event simulator)3 is a modular discrete event simulator implemented in C++. Getting started with it is quite simple, due to its clean design. OMNET++ also provides a powerful GUI library for animation and tracing and debugging support. Its major drawback is the lack of available protocols in its library, compared to other simulators. However, OMNET++ is becoming a popular tool and its lack of models is being cut down by recent contributions. For instance, a mobility framework has recently been released for OMNET++, and it can be used as a starting point for WSN modeling. Additionally, several new proposals for localization and MAC protocols for WSN have been developed with OMNET++ under the Consensus project, and the software is publicly available. Nevertheless, most of the available models have been developed by independent research groups and don’t share a common interface, which makes it difficult to combine them. 1.5.2.4

J-Sim

J-Sim (JavaSim)4 is a component-based simulation environment developed entirely in Java. It provides real-time process-based simulation. The main benefit of J-Sim is its considerable list of supported protocols, including a WSN simulation framework with a very detailed model of WSNs, and an implementation of localization, routing and data diffusion WSN algorithms. J-Sim models are easily reusable and interchangeable, offering the maximum flexibility. Additionally, it provides a GUI (Graphical user interface) library for animation, tracing and debugging support and a script interface named Jacl. 1.5.2.5

NCTUns2.0

NCTUns2.05 is a discrete event simulator whose engine is embedded in the kernel of a UNIX machine. The actual network layer packets are tunneled through virtual interfaces that simulate lower layers and physical devices. This notable feature allows simulations to be fed with real program data sources. A useful GUI is available in addition to a high number of protocols and network devices, including wireless LAN. Unfortunately, no specific designs for WSN are included. On one hand, the close relationship between the simulation engine of NCTUns2.0 and the Linux kernel machine seems a difficulty (adding WSN simulation modules to this architecture is not a straightforward task). But, on the other hand, real sensor data can be easily plugged into simulated devices, protocols and actual applications, just by installing these sensors in the machine. NCTUns2.0 also has worthy graphical edition capabilities. 1.5.2.6

JiST/SWANS

JiST (Java in Simulation Time)/SWANS (Scalable Wireless Ad hoc Network Simulator)6 is a discrete event simulation framework that embeds the simulation engine 3 www.omnetpp.org/ 4 https://www.physiome.org/jsim/ 5 http://nsl.csie.nctu.edu.tw/nctuns.html 6 http://jist.ece.cornell.edu/

18

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

in the Java byte code. Models are implemented in Java and compiled. Then, byte codes are rewritten to introduce simulation semantics. Afterwards, they are executed on a standard Java virtual machine (JVM). This implementation allows the use of unmodified existing Java software in the simulation, as occurs with NCTUns2.0 and UNIX programs. The main drawback of JiST tool is the lack of enough protocol models. At the moment it only provides an Ad-hoc network simulator called SWANS, built atop JiST engine, and with a reduced protocol support. The only graphical aid is an event logger. JiST claims to scale to networks of 106 wireless nodes with two and one order of magnitude better performance (execution time) than NS-2 and GloMoSim7 respectively. It also has been shown that it outperforms GloMoSim and NS-2 in event throughput and memory consumption, despite being built with Java. Parsec is a simulation language derived from C that adds semantics for creating simulation entities and message communication on a variety of parallel architectures. Taking advantage of parallelization, it has been shown to scale to 10,000 nodes. 1.5.2.7

TOSSIM

TOSSIM (Tiny operating system sensor network)8 is a bit-level discrete event simulator and emulator of TinyOS, i.e., for each transmitted or received bit an event is generated instead of one per packet. This is possible because of the reduced data rate (around 40 kbps) of the wireless interface. TOSSIM simulates the execution of nesC code on a TinyOS/MICA, allowing emulation of actual hardware by mapping hardware interruptions to discrete events. A simulated radio model is also provided. Emulated hardware components are compiled together with real TinyOS components using the nesC compiler. Thus, an executable with real TinyOS applications over a simulated physical layer is obtained. Additionally, there are also several communication services that provide a way to feed data from external sources. The result is a high fidelity simulator and emulator of a network of TinyOS/MICA nodes. The goal of TOSSIM is to study the behavior of TinyOS and its applications rather than performance metrics of some new protocol. Hence, it has some limitations; for instance, it does not capture energy consumption. Another drawback of this framework is that every node must run the same code. Therefore, TOSSIM cannot be used to evaluate some types of heterogeneous applications. TOSSIM can handle simulations around a thousand of motes. It is limited by its bit-level granularity: Performance degrades as traffic increases. Channel sampling is also simulated at bit level and consequently the use of a carrier sense multiple access (CSMA) protocol causes more overhead than a time division multiple access (TDMA) one. 1.5.2.8

EmStar/EmSim/EmTOS

EmStar9 is a software framework to develop WSN applications on special platforms called microservers: Ad hoc systems with better hardware than a conventional 7 networksimulationtools.com/glomosim-simulator-projects/ 8 networksimulationtools.com/tossim/ 9 https://www.usenix.org/legacy/publications/library/proceedings/usenix04/tech/general/full

/girod/girod html/eu.html

papers

SIMULATION TOOLS BASED ON HIGH PERFORMANCE

19

sensor. The EmStar environment contains a Linux microkernel extension, libraries, services and tools. The most important tools are: EmSim: A simulator of the microserver’s environment. In EmSim, every simulated node runs an Em-Star stack, and is connected through a simulated radio channel model. It is not a discrete event but a time-driven simulator; that is, there is no virtual clock. EmCee: An interface to real low-power radios, instead of a simulated radio model, obtaining radio emulation. EmStar source code (this code can be in any language) is used in the simulations. EmTOS: An extension of EmStar that enables nesC/TinyOS applications to run in an EmStar framework. Thus, it opens the way to heterogeneous systems of sensor and microservers. Simulation of microserver and sensor networks is also supported. In addition, EmTOS provides three modes of emulation: “Pure Emulation,” where all the motes are emulated by software, “Real Mode,” where all the motes are real, and “Hybrid Mode,” where some motes are real and others are emulated. EmTOS reaches up to 200 motes and it is claimed that for over 500 nodes it would be necessary to distribute the simulation on several processors. 1.5.2.9

ATEMU

ATEMU10 , which stands for “Atmel Emulator,” is a fine-grained sensor network simulator by Polley et al. ATEMU is described as a bridge between an actual deployment of a Wireless Sensor Network system, and a Wireless Sensor Network simulator, a hybrid simulator, where the operation of individual sensor nodes is emulated in an instruction by instruction manner, and their interactions with each other via wireless transmissions are simulated in a realistic manner [12]. Although it was not specifically designed for MICA2 motes and TinyOS, much of the research and testing of ATEMU was performed with this platform. It is an emulator of the AVR processor (this processor is used in the MICA platform). Although the operation of the mote is emulated instruction by instruction, the radio model is simulated. ATEMU also provides a library of other hardware devices, e.g., timers or transceivers. Therefore, a complete hardware platform is emulated, obtaining two advantages: 1. The capability of testing OS and applications other than TinyOS. 2. The capability of simulating heterogeneous networks with different sensors. They are achieved at the cost of high processing requirements and poor scalability. A key weakness to ATEMU is that it is significantly, approximately 30 times, slower that TOSSIM. 10 http://www.hynet.umd.edu/research/atemu/

20

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

1.5.2.10

SENS

SENS is a Wireless Sensor Network simulator that was developed by the Open Systems Laboratory at the University of Illinois at Urbana-Champaign (UIUC) in 2004. SENS was developed as a customizable sensor network simulator for WSN applications. It has four main components that function to simulate the sensor node and network, and the environments in which the network might operate. There is an application component that simulates the software of the sensor node; and a network component that simulates the transmission of packets among the nodes. It operates in one of three modes: successful packet transmission, a probability of packet loss, and packet collision. The third component is the physical component that simulates the power, sensor, and actuator parts of the sensor node and interface with the fourth component, the environment. The environment component is simulated by considering how different surfaces affect radio wave propagation. The environment simulation component is the key benefit of SENS; it is otherwise less customizable than other network simulators. This discrete event simulator is implemented in C++. SENS utilizes a simplified sensor model with three layers (application, network and physical) plus an additional combined environment and radio layer. NesC code can be used directly on it. 1.5.2.11

PROWLER/JPROWLER

PROWLER/JPROWLER is a discrete event simulator running under MATLAB intended to optimize network parameters. JPROWLER11 is a version of PROWLER (Probabilistic wireless network simulator) developed in Java. 1.5.2.12

SNAP

SNAP (Simulation analysis platform)12 is a totally different approach. SNAP is defined as an integrated hardware simulation and deployment platform. It is a microprocessor that can be used in two ways: 1. As the core of a deployed sensor. 2. As part of an array of processors that performs parallel simulation. Again, “real” code for sensors can be simulated. By combining arrays of SNAPs (called network on a chip), it is claimed to be able to simulate networks on the order of 100,000 nodes. 1.5.2.13

SensorSim

SensorSim13 is another network simulator, which is based on NS-2. This simulator was developed in the network and embedded systems laboratory at UCLA. Similar to the model power that is used in the minimize usage extend life (MUEL) simulator, SensorSim enhanced NS-2 by having an advanced power model, taking 11 https://w3.isis.vanderbilt.edu/projects/nest/jprowler/ 12 snap.stanford.edu/ 13 https://www.swmath.org/software/15014

SIMULATION TOOLS BASED ON HIGH PERFORMANCE

21

into account all of the components on a sensor node that would use energy. Further, a significant advancement of SensorSim was to include, first a sensor channel, and later, a mechanism that allowed the simulation of external events that would trigger a reaction in the simulation. Another significant contribution of SensorSim was the development of a middleware software tool called sensor ware. This middleware functioned between the simulator and the simulated sensor nodes, and allowed dynamic management of nodes during simulation, such as the loading of scripts or other applications to the nodes. SensorSim, having evolved from NS-2, had similar problems of scalability, and is not publicly available today.

1.5.2.14

SSFNET

SSFNET (Scalable simulation framework network) 14 is a collection of Java SSFbased components for modeling and simulation of Internet protocols and networks at and above the IP packet level of detail. Link layer and physical layer modeling can be provided in separate components. SSFNet models are self-configuring; that is, each SSFNet class instance can autonomously configure itself by querying a configuration database, which may be locally resident or available over the Web. The network configuration files are in the DML format. They are used to configure a complete model, and instantiate a simulation with the help of the scalable DML configuration database package that is distributed with the SSF simulators. The principal classes used to construct virtually any Internet model are organized into two derivative frameworks, SSF.OS (for modeling of the host and operating system components, esp. protocols) and SSF.Net (for modeling network connectivity, creating node and link configurations). The frameworks SSF.OS and SSF.Net hide all details of the discrete event simulator SSF API, allowing the same implementation of protocols as in a real operating system.

1.5.2.15

Ptolemy

The Ptolemy15 project studies modeling, simulation, and design of concurrent, real-time, embedded systems. The focus is on assembly of concurrent components. The key underlying principle in the project is the use of well-defined models of computation that govern the interaction between components. A major problem area being addressed is the use of heterogeneous mixtures of models of computation. A software system called Ptolemy II is being constructed in Java. The work is conducted in the industrial cyber-physical systems center (iCyPhy) in the department of electrical engineering and computer sciences of the University of California at Berkeley. The project is directed by Prof. Edward Lee. The project is named after Claudius Ptolemaeus, the second century Greek astronomer, mathematician, and geographer. 14 www.ssfnet.org 15 https://ptolemy.berkeley.edu/

22

1.6

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

Conclusion

Propagation is a principal tool to consider remote sensor systems in context of authentic analysis. This particular analysis suggests methods to detect recurrences in wireless sensor network and is also used for model representation every time the tool has been used. According to the concept of the models, OMNET++16 (Object-oriented modular discrete event simulator) and SSFNET17 (Scalable simulation framework network) limitations of open tradition models diverge from various test frameworks (uncommonly, NS-2), which constructs progression time. Mechanical assemblies like NCTU NS2.0 (Network Simulation 2.0), Linux operating system or Java platform are independently used in a propagation. At this stage, potential results immensely increase. In practice, mechanical assemblies, for instance, TOSSIM18 (Tiny operating system sensor network), EmTOS or ATEMU, can reproduce certifiable sensor code. In any case, late test framework shows that suitable software (JiST/SWAN) results in a performance that is higher than network simulation and GloMoSim19 (in its back-to-back shape). Unmistakably, parallel simulations should perform and scale better than back-to-back ones. Parallel test frameworks, such as GloMoSim (whose goal is execution instead of flexibility), can reenact up to the limit of ten thousand remote center points. The standard aim of DASSF (Digital access signaling system Fi) parallel mechanical assembly is flexibility, with supportive topology arrangements as sweeping as hundred hundreds of wired parts. Graphical support is given by all the groups. OMNET++, NCTU NS2.0, J-SIM (Simulation) and Ptolemy software provide momentous GUI (Graphical user interface) libraries for development as well as investigation. This chapter gave a clear explanation on the importance of simulation and how the process of simulation goes from scratch to the next level by implementing basic programming. We focused on explaining the whole concept with basic programming like Java and in some places we utilized Python code for making the models’ design and implementing simple theories of the networking. We started with a discussion on MATLAB modeling and simulations and continued with a discussion on the types of simulations needed. Next, discrete event simulation using MATLAB was explained in brief. Then, the simulation software used for the modeling and simulation was explained and finally the tools used for high performance computing using network simulation methodology were explained. 16 www.omnetpp.org/ 17 www.ssfnet.org 18 networksimulationtools.com/tossim/ 19 networksimulationtools.com/glomosim-simulator-projects/

CONCLUSION

23

REFERENCES 1. Banks, J., & Gibson, R. (1997). Simulation modeling: some programming required. IIE Solutions, 29, 26-31. 2. Hlupic, V., & Paul, R. J. (1999). Guidelines for selection of manufacturing simulation software. IIE transactions, 31(1), 21-29. 3. Nikoukaran, J., Hlupic, V., & Paul, R. J. (1999). A hierarchical framework for evaluating simulation software. Simulation Practice and Theory, 7(3), 219-231. 4. Tewoldeberhan, T. W., Verbraeck, A., Valentin, E., & Bardonnet, G. (2002, December). An evaluation and selection methodology for discrete-event simulation software. In Simulation Conference, 2002. Proceedings of the Winter (Vol. 1, pp. 67-75). IEEE. 5. Seila, A. F., Ceric, V., & Tadikamalla, P. R. (2003). Applied simulation modeling. Brooks/Cole. 6. Popovi, A., Hackney, R., Coelho, P. S., & Jakli, J. (2012). Towards business intelligence systems success: Effects of maturity and culture on analytical decision making. Decision Support Systems, 54(1), 729-739. 7. Ahloowalia, B. S., Maluszynski, M., & Nichterlein, K. (2004). Global impact of mutation-derived varieties. Euphytica, 135(2), 187-204. 8. Ahn, S.; Mukelar, A. Rice Blast Management Under Upland Conditions. Progress in Upland Rice Research; Int. Rice Res. Inst.: Manila, 1986; pp 363-374. 9. Aktar, M. W.; Sengupta, D.; Chowdhury, A. Impact of Pesticides Use in Agriculture: Their Benefits and Hazards. Interdiscip. Toxicol. 2009, 2, 1-12. 10. Paluszek, M., & Thomas, S. (2019). MATLAB Graphics. In MATLAB Machine Learning Recipes (pp. 45-71). Apress, Berkeley, CA. 11. Henriksson, D., Cervin, A., & Arzn, K. E. (2003, October). TrueTime: Real-time control system simulation with MATLAB/Simulink. In Proceedings of the Nordic MATLAB Conference. Copenhagen, Denmark. 12. Pathan, A. S. K., Monowar, M. M., & Khan, S. (2014). Simulation technologies in networking and communications: selecting the best tool for the test. CRC Press. 13. Law, A. M., Kelton, W. D., & Kelton, W. D. (1991). Simulation modeling and analysis (Vol. 2). New York: McGraw-Hill. 14. Chang, X. (1999). Network simulations with OPNET. In WSC’99. 1999 Winter Simulation Conference Proceedings. Simulation-A Bridge to the Future (Cat. No. 99CH37038) (Vol. 1, pp. 307-314). IEEE. 15. Jain, R. (1990). The art of computer systems performance analysis: techniques for experimental design, measurement, simulation, and modeling. John Wiley & Sons. 16. Law, A. M., Kelton, W. D., & Kelton, W. D. (2000). Simulation modeling and analysis (Vol. 3). New York: McGraw-Hill. 17. Jain, R. (1990). The art of computer systems performance analysis: techniques for experimental design, measurement, simulation, and modeling. John Wiley & Sons. 18. Shah, R. C., Roy, S., Jain, S., & Brunette, W. (2003). Data mules: Modeling and analysis of a three-tier architecture for sparse sensor networks. Ad Hoc Networks, 1(2-3), 215233.

24

INTRODUCTION TO MODELING, SIMULATIONS AND ANALYSIS

19. Fortier, P. J. (2018). Modeling and Analysis of Local Area Networks, CRC Press. 20. Sommer, C., Eckhoff, D., Brummer, A., Buse, D. S., Hagenauer, F., Joerer, S., & Segata, M. (2019). Veins: The open source vehicular network simulation framework. In Recent Advances in Network Simulation (pp. 215-252). Springer, Cham. 21. Aktas, I., King, T., & Mengi, C. (2010). Modeling application traffic. In Modeling and Tools for Network Simulation (pp. 397-426). Springer, Berlin, Heidelberg. 22. Frasconi, P., & Smyth, P. (2003). Modeling the Internet and the Web: probabilistic methods and algorithms. Wiley. 23. Burbank, J. L., Kasch, W., & Ward, J. (2011). An introduction to network modeling and simulation for the practicing engineer (Vol. 5). John Wiley & Sons. 24. Surez, F. J., Nuo, P., Granda, J. C., & Garca, D. F. (2015). Computer networks performance modeling and simulation. In Modeling and Simulation of Computer Networks and Systems (pp. 187-223). Morgan Kaufmann. 25. Guizani, M., Rayes, A., Khan, B., & Al-Fuqaha, A. (2010). Network modeling and simulation: a practical perspective. John Wiley & Sons.

CHAPTER 2

INTRODUCTION TO MATLAB PROGRAMMING

Abstract In this chapter, we have tried to show the power of MATLAB for computational mathematics, followed by a detailed description of the features. Also discussed in detail are the various areas in which MATLAB is used. We discuss the various notations, operators and syntax along with hands-on practical examples and various loop structures and decision controls, import and export operations, use and creation of M-files, different types of plotting and graphs, etc. We also explain the various clones of MATLAB. This chapter will effectively help readers understand the workings and uses as well as applications of MATLAB more clearly. Keywords: MATLAB features, toolbox in MATLAB, functionalities in MATLAB, scilab

Network Modeling, Simulation and Analysis in MATLAB. c 2019 Scrivener Publishing By Dac-Nhuong Le et al. Copyright 

25

26

2.1

INTRODUCTION TO MATLAB PROGRAMMING

Introduction

MATLAB (Matrix Laboratory) is a fourth-generation, high-level programming language for numerical computation, visualization and programming, which can interact with the environment [1-4]. MATLAB was developed by MathWorks.1

Figure 2.1

MathWorks MATLAB R2018b

MATLAB’s power lies in the fact that it is used for every facet of computational mathematics. Some of the mathematical calculations that are commonly used are: Matrices Calculations Array Processing Two-Dimensional Plotting Three-Dimensional Plotting Curve Fitting Linear Algebraic Calculations Numerical Calculations Usage of Nonlinear Functions Transformations Statistical and Data Analysis Calculus Equations Integration Process Differential Equations Curve Fitting 1 https://www.mathworks.com/

BASIC FEATURES

2.2

27

Basic Features

2.2.1

Features of MATLAB

For numerical calculation, perception and application advancement, MATLAB is one of the nonstandard state languages. A collaborative environment for iterative investigation, the outlining of roles as well as critical thinking is provided by MATLAB. MATLAB optimizes a design to meet a custom objective and creates custom plots for devices. MATLAB’s modifying interface improves devices by enhancing code, model practicality, and by boosting execution. 2.2.2

Uses of MATLAB

A range of the following applications are used in MATLAB:2 Signal Processing Communications System Image Processing Video Processing Control Systems Testing Measurement Computational Finance Computational Biology

2.3

Notation, Syntax, and Operations

The MATLAB environment behaves like a super-complex calculator and commands can be given in the window named Command Prompt as >>. It is one of the interpreted environments which MATLAB also executes in the right way if you give the commands [5, 6]. 2.3.1

Practical Examples for MATLAB

Give an expression for the concept of instance, 1

5+5

Then click ENTER in the menu. 2 https://www.tutorialspoint.com/matlab/matlab

overview.htm

28

INTRODUCTION TO MATLAB PROGRAMMING

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E) and the result is 1

ans = 10

Let us take some more examples 1

3ˆ2 % 3 raised to the power of 2

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E). OUTPUT 1

ans = 9

One more sample, 1

sin(pi / 2) % sine of angele 90 degree

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E). OUTPUT 1

ans = 1

Another example, 1

7/0 % Divide by zero

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E). OUTPUT 1 2

Ans = Inf Warning: division by zero

Another example, 1

732 * 20.3

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E). OUTPUT 1

ans = 1.4860e+04

2.3.2

Use of Semicolon (;) in MATLAB

For an articulation, include a semicolon after articulation in the event that you need to control and hide the MATLAB yield and a semicolon (;) to show the end of explanation. For example, 1 2

x = 3 y = x + 5

NOTATION, SYNTAX, AND OPERATIONS

29

MATLAB executes immediately once the Execute button is pressed or while given as (Ctrl+E). OUTPUT 1

y = 8

2.3.3

Adding Comments

For indicating a comment line, the percent symbol (%) is used. For example, 1

x = 9 % assign the value 9 to x

Using the block comment operators % {and %} and here block of comments are also possible to write. To assist you with adding, expel or change the configuration of remarks, the devices and the setting menu objects are incorporated into the MATLAB supervisor. 2.3.4

Commonly Utilized Operators and Special Characters

MATLAB bolsters the accompanying commonly utilized administrators and unique characters. Table 2.1

Operators and special characters.

30

INTRODUCTION TO MATLAB PROGRAMMING

2.3.5

Unique Variables and Constants

MATLAB underpins the accompanying unique factors and constants Table 2.2

2.3.6

Unique variables and constants.

Sparing Process

For sparing every one of the factors in the workspace, spare summons is utilized as a record with tangle expansion in the present index. For example: 1

save my life

By using the load command the reload process will be activated. This process is possible at anytime. 1

load my life

2.3.7

MATLAB Decisions

The developer ought to indicate at least one condition to be assessed or tried by the program which is required by the basic leadership structures, and if the condition is resolved to be valid, along with an announcement or articulations to be executed, and different proclamations are executed in case if the condition is false [7, 8].

Figure 2.2

MATLAB decision.

NOTATION, SYNTAX, AND OPERATIONS

31

In vast maximum programming dialects, the general type of an average basic leadership structure is found. MATLAB gives the accompanying sorts of basic leadership articulations and to check their detail taps the accompanying connections. To explain the operations in MATLAB we can consider the following table for clarification. Table 2.3

2.3.8

Variables and constants.

MATLAB Loops

There may be a circumstance where a block of code is executed a specific number of times, and as a rule the announcements are executed continuously [9-12]. In this case the primary proclamation is executed first, trailed constantly, etc. The few control structures which are given by the programming dialects take into consideration more convoluted ways of execution. Executing an announcement or gathering of proclamations in numerous events is permitted by a circle articulation and the general structure of the circle is explained in the vast majority of the programming dialects as

Figure 2.3

MATLAB loops.

32

INTRODUCTION TO MATLAB PROGRAMMING

Table 2.4

Table 2.5

Articulations.

Loop control statements.

For example, 1 2

x = 3 y = x + 5

2.4

Import and Export Operations

2.4.1

Import Data in MATLAB

In MATLAB the loading data from an external file is known as import data. By using the IMPORT DATA function different formats of several data files are loaded. Syntax: A = importdata(filename) A = importdata(’-pastespecial’) A = importdata(___,delimiterIn) A = importdata(___,delimiterIn,headerlinesIn) [A,delimiterOut,headerlinesOut] = importdata(___) Description A = importdata(filename) loads data into array A. A = importdata(’-pastespecial’) loads data from the system clipboard rather than from a file. A = importdata(___, delimiterIn) interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes.

IMPORT AND EXPORT OPERATIONS

33

A = importdata(___, delimiterIn, headerlinesIn) loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1. [A, delimiterOut, headerlinesOut] = importdata(___) additionally returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes. Example 2.4.1 Load and show a picture document. Make a content record and sort the accompanying code in it. 1 2 3

filename = ’smile.jpg’; A = importdata(filename); image(A);

Execute the record, it shows picture document. Nonetheless, we should save in present index. Simulation result:

Example 2.4.2 Import a content record as well as determine Delimiter and Header for all the columns. Weeklydata.txt file 1 2 3 4 5 6

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

PROGRAM 1 2 3 4 5

filename =’weeklydata.txt’; delimiterIn = ’ ’; headerlinesIn =1; A = importdata(filename,delimiterIn,headerlinesIn);

34 6 7 8 9 10 11

INTRODUCTION TO MATLAB PROGRAMMING

%View data for k =[1:7] disp(A.colheaders{1, k}) disp(A.data(:, k)) disp(’ ’) end

OUTPUT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

SunDay 95.0100 73.1100 60.6800 48.6000 89.1300 Monday 76.2100 45.6500 41.8500 82.1400 44.4700 Tuesday 61.5400 79.1900 92.1800 73.8200 57.6300 Wednesday 40.5700 93.5500 91.6900 41.0300 89.3600 Thursday 55.7900 75.2900 81.3200 0.9900 13.8900 Friday 70.2800 69.8700 90.3800 67.2200 19.8800 Saturday 81.5300 74.6800 74.5100 93.1800 46.6000

IMPORT AND EXPORT OPERATIONS

35

Example 2.4.3 Import from clipboard. Arithmetic straightforward: Make content document then sort the accompanying program. 1

A = importdata(’-pastespecial’)

The following result will be shown if you run the document 1 2

A = ’Mathematics is simple.’

Low-Level File I/O: Abnormal state work is the import information work. To control overly perusing or composing information to a record, MATLAB permits low-level document I/O capacities. To work proficiently, these capacities require more point-by-point data about your record. MATLAB gives the accompanying capacities to peruse and compose activities at the byte or character level. Table 2.6

Low-level file I/O functions.

Function

Description

close

Close one or all open files

feof

Test for end-of-file

ferror

Information about record I/O errors

fgetl

Read line from the data, removing newline characters

fgets

Read line from the file, keeping newline characters

fopen

Open the file, or obtain information about open files

fprintf

Write data to a text file

fread

Read data from binary file

frewind

Move file position indicator to the begin of the open file

fscanf

Read data from the text file

fseek

Move to the specified position in the file

ftell

Position in open file

fwrite

Write data to the binary file

Import Text Data Files with Low-Level I/O: MATLAB provides the following functions for low-level import of text data files. The fscanf function reads formatted data in a text or ASCII file. The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line. The fread function reads a stream of data at the byte or bit level. Example: We have a text data file ’myfile.txt’ saved in our working directory - the file stores rainfall data for three months; June, July, and August for the year 2012.

36

INTRODUCTION TO MATLAB PROGRAMMING

The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months. M; so, we have M sets of measurements. The file looks like this 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Rainfall Data Months: June, July, August M = 3 12:00:00 June-2012 17.21 28.52 39.78 16.55 23.67 19.15 0.35 17.57 NaN 12.01 17.92 28.49 17.40 17.06 11.09 9.59 9.33 NaN 0.31 0.23 10.46 13.17 NaN 14.89 19.33 20.97 19.50 17.65 14.45 14.00 18.23 10.34 17.95 16.46 19.34 09:10:02 July-2012 12.76 16.94 14.38 11.86 16.89 20.46 23.17 NaN 24.89 19.33 30.97 49.50 47.65 24.45 34.00 18.23 30.34 27.95 16.46 19.34 30.46 33.17 NaN 34.89 29.33 30.97 49.50 47.65 24.45 34.00 28.67 30.34 27.95 36.46 29.34 15:03:40 August-2012 17.09 16.55 19.59 17.25 19.22 17.54 11.45 13.48 22.55 24.01 NaN 21.19 25.85 25.05 27.21 26.79 24.98 12.23 16.99 18.67 17.54 11.45 13.48 22.55 24.01 NaN 21.19 25.85 25.05 27.21 26.79 24.98 12.23 16.99 18.67

We will import data from this file and display this data. Take the following steps: Open the file with fopen function and get the file identifier. Describe the data in the file with format specifiers, such as ’%s’ for a string, ’%d’ for an integer, or ’%f’ for a floating-point number. To skip real characters in the file, include them in the format description. To skip a data field, use an asterisk (’*’) in the specifier. For example, to read the headers and return the single value for M, we write 1

M =fscanf(fid,’%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n’,1);

By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use the loop for reading three sets of data, and each time; it will read seven rows and five columns.

IMPORT AND EXPORT OPERATIONS

37

We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array. Create a script file and type the following code in it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

filename =’/data/myfile.txt’; rows =7; cols =5; fid = fopen(filename);% open the file % read the file headers, find M (number of months) M =fscanf(fid,’%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n’,1); % read each set of measurements for n =1:M mydata(n).time= fscanf(fid, ’%s’,1); mydata(n).month= fscanf(fid, ’%s’,1); % fscanf fills the array in column order, %so transpose the results mydata(n).raindata=... fscanf(fid, ’%f’,[rows, cols]); end for n =1:M disp(mydata(n).time), disp(mydata(n).month) disp(mydata(n).raindata) end fclose(fid);% close the file

When you run the file, it displays the following result 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

12:00:00 June-2012 17.2100 17.5700 11.0900 13.1700 14.4500 28.5200 NaN 9.5900 NaN 14.0000 39.7800 12.0100 9.3300 14.8900 18.2300 16.5500 17.9200 NaN 19.3300 10.3400 23.6700 28.4900 0.3100 20.9700 17.9500 19.1500 17.4000 0.2300 19.5000 16.4600 0.3500 17.0600 10.4600 17.6500 19.3400 09:10:02 July-2012 12.7600 16.9400 14.3800 11.8600 16.8900 20.4600 23.1700

NaN 34.0000 33.1700 24.4500 24.8900 18.2300 NaN 34.0000 19.3300 30.3400 34.8900 28.6700 30.9700 27.9500 29.3300 30.3400 49.5000 16.4600 30.9700 27.9500 47.6500 19.3400 49.5000 36.4600 24.4500 30.4600 47.6500 29.3400

15:03:40 August-2012 17.0900 13.4800 27.2100 11.4500 25.0500 16.5500 22.5500 26.7900 13.4800 27.2100 19.5900 24.0100 24.9800 22.5500 26.7900

38

INTRODUCTION TO MATLAB PROGRAMMING

26 27 28 29

17.2500 19.2200 17.5400 11.4500

2.4.2

NaN 12.2300 24.0100 24.9800 21.1900 16.9900 NaN 12.2300 25.8500 18.6700 21.1900 16.9900 25.0500 17.5400 25.8500 18.6700

Export Data in MATLAB

Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options. You can create the following types of files: Rectangular, delimited ASCII data file from an array. Diary (or log) file of keystrokes and the resulting text output. Specialized ASCII file using low-level functions such as fprintf. MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format. Apart from this, you can also export data to spreadsheets. There are two ways to export a numeric array as a delimited ASCII data file: Using the save function and specifying the -ASCII qualifier. Using the dlmwrite function. The syntax for using the save function is 1

Save my_data.out num_array -ascii

where my_data.out is the delimited ASCII data file created, num_array is a numeric array and - ascii is the specifier. The syntax for using the dlmwrite function is 1

dlmwrite(’my_data.out’, num_array, ’dlm_char’)

where my_data.out is the delimited ASCII data file created, num_array is a numeric array, and dlm_char is the delimiter character. Example: The following example demonstrates the concept. Create a script file and type the following code 1 2 3 4 5

num_array =[1234;4567;7890]; save array_data1.out num_array -ascii; type array_data1.out dlmwrite(’array_data2.out’, num_array,’ ’); type array_data2.out

When you run the file, it displays the following result:

IMPORT AND EXPORT OPERATIONS

1 2 3 4 5 6 7

39

1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00 4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00 7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00 1 2 3 4 4 5 6 7 7 8 9 0

Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can Either, convert the cell array to a matrix using the cell2mat function Alternatively, export the cell array using low-level file I/O functions. If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file. For example, let us write the word ’hello’ to a file. 1 2 3

h =’hello’; Save textdata.out h -ascii type textdata.out

MATLAB executes the above statements and displays the following result, which is the characters of the string ’hello’ in 8-digit ASCII format. 1 2

1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02

Writing to Diary Files: Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics. To turn on the diary function, type: 1

diary

Optionally, you can give the name of the log file, say 1

Diary logdata.out

To turn off the diary function 1

diary off

You can open the diary file in a text editor. Exporting Data to Text Data Files with Low-Level I/O: So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function. As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as ’w’ or ’a.’

40

INTRODUCTION TO MATLAB PROGRAMMING

After processing the file, you need to close it with fclose(fid) function. The following example demonstrates the concept. Example: Create a script file and type the following code in it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

% create a matrix y, with two rows x = 0:10:100; y =[x; log(x)]; % open a file for writing fid =fopen(’logtable.txt’, ’w’); % Table Header fprintf(fid, ’Log Function\n\n’); %print values in column order % two values appear on each row of the file fprintf(fid,’%f %f\n’, y); fclose(fid); % display the file created Type logtable.txt

When you run the file, it displays the following result. 1 2 3 4 5 6 7 8 9 10 11 12 13

Log Function 0.000000 -Inf 10.000000 2.302585 20.000000 2.995732 30.000000 3.401197 40.000000 3.688879 50.000000 3.912023 60.000000 4.094345 70.000000 4.248495 80.000000 4.382027 90.000000 4.499810 100.000000 4.605170

2.5

Elements

After signing windowing domain by composing MATLAB at the UNIX incite you may start up MATLAB. 2.5.1

Commands

Some essential UNIX charges can keep running in the MATLAB provoke, for example, disc and ls. You can see the UNIX Documentation Page for more insights about UNIX summons. In the event that you need assistance, as a rule MATLAB enables sort to help at inciting to get a rundown of assistance themes. Sort help at provoke to get help on a particular kind or capacity by supplanting with theme or otherwise capacity according to your wish regarding help.

ELEMENTS

41

Sort exit at provokes to leave the MATLAB.

Figure 2.4

2.5.2

MATLAB elements.

MATLAB Basics

To work with networks a MATLAB is planned, in which a lattice is characterized to be a rectangular exhibit of numbers. MATLAB does not require any compose presentations or measurement explanations dissimilar to programming dialects, for example, C or Java [10]. MATLAB consequently produces the variable and assigns the suitable measure of capacity when it meets another variable name. Sort the summon at provoke to verify the factors which exist as of now and furthermore to see the measurements. Enter the option clear to free the memory. Just compose variable name at incite, which makes variables is trailed by the equivalents sign (=), and taken after by the instatement, as exhibited below: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

PROGRAM To initialize a scalar a: >>a=[2] To initialize a row vector b: >>b=[1 2 3 4 5] Note that spaces between numbers signify a new column. To initialize a column vector c: >>c=[6; 7; 8; 9] Note that semicolons between numbers signify a new row. To initialize a three by three matrix M: >>M=[1 2 3; 4 5 6; 7 8 9] Again, spaces between numbers signify a new column, whereas semicolons signify a new row.

42

INTRODUCTION TO MATLAB PROGRAMMING

2.5.3

Creating Matrices

MATLAB provides four capacities that enable you to effortlessly produce essential networks. The zeros capacity makes a network with all components equivalent to the value 0. Example 2.5.1 Make a (3 by 4) zeros network which is represented as Z: 1

>> Z = zeros (3, 4)

Capacity makes network with all components equivalent to the value 1. Example 2.5.2 Make a (2 by 3) ones network is represented as O: 1

>> O = ones (2, 3)

The rand work makes the framework consistently disseminate irregular components. Example 2.5.3 Make a (4 by 1) irregular lattice is represented as R: 1

>>R= rand(4, 1)

The randn work makes a framework of regularly disseminated irregular components. For instance, making a (2 by 5) irregular network is represented as R: 1

>>R= randn(2, 5)

2.5.4

Framework Operations

Some framework operations provided by MATLAB are shown in Table 2.7. Table 2.7

Framework operations.

Operations

Description

+

Matrix addition

-

Matrix subtraction

.

Takes the transpose of the matrix

Dot product inv

Take the inverse of a matrix

eig

Computes the eigenvalues of the square matrix

det

Computes the determinant of a matrix

reff

Calculates the reduced row echelon form of a matrix

Example 2.5.4 Create an array, A, and add a scalar value to it.

ELEMENTS

1 2 3 4 5 6 7

43

A = [0 1; 1 0]; C = A + 2 %Result C = 22 2 3 3 2

Example 2.5.5 Create two arrays, A and B, and add them together. 1 2 3 4 5 6 7 8

A = [1 0; 2 4]; B = [5 9; 2 1]; C = A + B %Result C = 22 6 9 4 5

Example 2.5.6 Create an array, A, and subtract a scalar value from it. 1 2 3 4 5 6 7

A = [2 1; 3 5]; C = A - 2 %Result C = 22 0 -1 1 3

Example 2.5.7 Create two arrays, A and B, and subtract the second, B, from the first, A. 1 2 3 4 5 6 7 8

A = [1 0; 2 4]; B = [5 9; 2 1]; C = A - B %Result C = 22 -4 -9 0 3

Example 2.5.8 Create two simple, three-element vectors. 1 2

A = [4 -1 2]; B = [2 -2 -1];

Calculate the dot product of A and B. 1 2

C = dot(A,B) C = 8

44

INTRODUCTION TO MATLAB PROGRAMMING

The result is eight since C = A(1)*B(1) + A(2)*B(2) + A(3)*B(3) Create a matrix of real numbers and compute its transpose. B has the same elements as A, but the rows of B are the columns of A, and the columns of B are the rows of A. 1 2 3 4 5 6 7

A = magic(4)

1 2 3 4 5 6 7

B = A.’

A = 44 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

B = 44 16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1

Example 2.5.9 Compute the inverse of a 3-by-3 matrix. 1 2 3 4 5 6

X = [1 0 2; -1 5 0; 0 3 -9] X = 33

1 2 3 4 5 6

Y = inv(X) Y = 33

1 0 2 -1 5 0 0 3 -9

2.5.5

0.8824 -0.1176 0.1961 0.1765 0.1765 0.0392 0.0588 0.0588 -0.0980

Using M-Files

M-Files develop the script as well as define the functions in external files which can be allowed by MATLAB. To execute the file at the MATLAB prompt, type the filename without the .m extension and M-Files have the file extension .m. You can use the MATLAB editor or any other text editor to create your .m files. In this section, we will discuss the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line.

ELEMENTS

2.5.5.1

45

Creating and Running Script Files

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). 1 2 3

edit Or edit

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 (>>). 1 2 3

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 the first time, MATLAB prompts you to confirm it. Click Yes. Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code.

Figure 2.5

Create an M-File.

Type the following code in the editor: 1 2 3 4 5 6 7

NoOfStudents=6000; TeachingStaff=150; NonTeachingStaff=20; Total=NoOfStudents+TeachingStaff... +NonTeachingStaff; disp(Total);

46

INTRODUCTION TO MATLAB PROGRAMMING

After creating and saving the file, you can run it in two ways: Clicking the Run button on the editor window or Just typing the filename (without extension) in the command prompt: >> prog1 The command window prompt displays the result: 1

6170

Example 2.5.10 Create a script file and type the following code. 1 2 3 4 5

a c d e f

=5; b =7; = a + b = c + sin(b) =5* d = exp(-d)

When the above code is compiled and executed, it produces the following result: 1 2 3 4

c d e f

= = = =

2.5.5.2

12 12.657 63.285 3.1852e-06

MATLAB Toolboxes

At USC, the following MATLAB toolboxes are available: Control Systems Fuzzy Logic Image Processing LMI Control Neural Networks Optimization Partial Differential Equation Robust Control Signal Processing Statistics Symbolic Math System Identification Wavelets To get into Toolbox\MATLAB Start menu\Toolboxes submenu, at that point -> Toolbox which you desire to utilize.

PLOTTING

Figure 2.6

2.6

47

How to add new toolbox to MATLAB.

Plotting

To plot a chart for capacity, make the accompanying strides: Define x for the determination of scope of qualities for the variable x, Define y as y = f (x) is the capacity calculation. Use the code plot(x, y) Code: 1 2 3

x=[0:5:100]; y = x; plot(x, y)

Simulation result:

Let us take one more example to plot the function y = x2 . In this example, we will draw two graphs with the same function, but in the second one, we will reduce the value of increment. Please note that as we decrease the increment, the graph becomes smoother.

48

INTRODUCTION TO MATLAB PROGRAMMING

Create a script file and type the following code: 1 2 3 4

x=[12345678910]; x=[-100:20:100]; y= x.ˆ2; plot(x, y)

Simulation result:

Change the code file a little, reduce the increment to 5. Code: 1 2 3

x=[-100:5:100]; y = x.ˆ2; plot(x, y)

Simulation result:

2.6.1

Including Various Types of Graphs

MATLAB enables the inclusion of title, marks x-hub and y-pivot and network lines. X-label and y-label orders create names x-pivot and y-hub. The title will be displayed in the chart. The framework enables lattice in the output to be displayed. The pivot rises to charge permits creating the plot. The hub square order is the process which is used to create a square plot.

PLOTTING

49

Example 2.6.1 Create a script file and type the following code 1 2 3 4

x =[0:0.01:10]; y = sin(x); plot(x, y), xlabel(’x’), ylabel(’Sin(x)’), title(’Sin(x) Graph’), grid on, axis equal

MATLAB generates the following graph

2.6.2

Creation of a Multiple Number of Functions in a Similar Graph

Draw various diagrams in a similar plot. Make a content document and sort the accompanying code. Example 2.6.2 Create a script file and type the following code. 1 2 3 4

x =[0:0.01:10]; y = sin(x); g = cos(x); plot(x, y, x, g,’.-’), legend(’Sin(x)’,’Cos(x)’)

MATLAB generates the following graph

50

INTRODUCTION TO MATLAB PROGRAMMING

2.6.3

Creating a Graph According to Various Colors

MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes. Table 2.8

Setting colors.

Code

Color

w

White

k

Black

b

Blue

r

Red

c

Cyan

g

Green

m

Magenta

y

Yellow

Example 2.6.3 Let us draw the graph of two polynomials. f (x) = 3x4 + 2x3 + 7x2 + 2x + 9 and g(x) = 5x3 + 9x + 2 Create a script file and type the following code 1 2 3 4

x=[-10:0.01:10]; y= 3*x.ˆ4 + 2 * x.ˆ3 + 7 * x.ˆ2 + 2 * x + 9; g= 5 * x.ˆ3 + 9 * x + 2; plot(x, y,’r’, x, g,’g’)

When you run the file, MATLAB generates the following graph.

UNCOMMON FUNCTION

2.7

51

Uncommon Function

To play out an undertaking, capacity is a gathering together of explanations, and the sizes are characterized in independent records in MATLAB. The record name and the size ought to be the same in MATLAB capacities [10]. Nearby workspace is characterized as the capacities work without anyone else’s workspace. Base workspace is characterized as discrete from the workspace summon incite. Punctuation of a capacity proclamation is function[out1,out2,.., outN]=myfun(in1,in2,.., inN) Example 2.7.1 The following function named mymax should be written in a file named mymax.m. It takes five numbers as an argument and returns the maximum of the numbers. Create a function file, named mymax.m and type the following code in it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

function max =mymax(n1, n2, n3, n4, n5) %Thisfunction 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

The principal code of capacity begins with catchphrase work. It works to provide the suitable name of the capacity which requests contentions. Here, the program work has 5 information contentions and 1 yield contention. 1

help mymax

OUTPUT 1 2

This function calculates the maximum of the five numbers are given as input

You can call the function as CODE 1

mymax(34, 78, 89, 23, 11)

OUTPUT 1

ans = 89

52

INTRODUCTION TO MATLAB PROGRAMMING

Unknown capacity is characterized inside a solitary MATLAB proclamation, and in customary programming dialects, it resembles an inline work. This capacity contains any number of info and yield contentions, and it is a solitary MATLAB articulation. An unknown capacity can be characterized at the right of the MATLAB order line or inside a capacity or content. The linguistic structure for making a mysterious capacity from an articulation is 1

f = @(arglist)expression

Example 2.7.2 Here we will write an anonymous function named power, which will take two numbers as input and return the first number raised to the power of the second number.

Create a script file and type the following code in it. 1 2 3 4 5

power =@(x, n) x.ˆn; result1 =power(7,3) result2 =power(49,0.5) result3 =power(10,-10) result4 = power (4.5,1.5)

When you run the file, it displays 1 2 3 4

2.8

result1 result2 result3 result4

= = = =

343 7 1.0000e-10 9.5459

Executable Files Generation

As an alternative to the charge line system, you can fabricate a free executable with the convey device Graphical User Interface. At the MATLAB incite, enter convey apparatus. This dispatches a trade box, inciting you to describe an endeavor name for this autonomous shape. Supplant the "untitled1.prj" with your favored endeavor name, for instance, "myStandalone.prj." There are two tabs: the default newer tab will present in one side and on the other side you can see an Open tab. Here Open tab consists of some existing exercises for adjustment [19]. The accompanying images were created with MATLAB R2013a3 . 3 https://www.mathworks.com/help/matlab/release-notes-R2013a.html

EXECUTABLE FILES GENERATION

Figure 2.7

53

Initializing deploy tool in MATLAB.

Remember to replace the undertaking name untitled1.prj with your name decision, as myStandalone.prj. After pressing OK, the following discourse box shows up...

Figure 2.8

Initializing standalone application.

Press Add precise record prompts for the essential report name and its zone, for our purpose myStandalone.m in the present registry. The photograph above shows Removes major archive in light of the way that the precise record has quite recently been incorporated. The executable will be named, as usual, myStandalone. The Package tab exhibits what to make for this specific shape. Additional records and coordinators related with this errand may be entered by pressing the Add archives/envelopes. Here, the myApp.m has been incorporated. Frequently, the undertaking acknowledged will require you to open all instrument compartments. Tap the right-most (Actions) image (trailed by Settings, by then Toolboxes on Path) if you have to dismiss some of them. Futile apparatus compartments could save arrange time and memory accumulating.

54

INTRODUCTION TO MATLAB PROGRAMMING

Figure 2.9

Initilazing toolboxes required.

At the point when all the central records and envelopes required for the errand have been described, you may keep on constructing the executable by tapping on the farthest left light blue Build image (with two downward hits) near the upper right of the trade box. 2.9

Calling and Accumulating Executable Documents

This technique is the easiest method to incorporate MATLAB content into an independent executable. The means are depicted utilizing the accompanying example content, find R.m: 1 2 3 4 5 6

function R = findR % findR - given data T, Calculate R %------------------------------------------------------------------T = 10; R =.5 * (-9.8)*T %end of MATLAB Code

Complete these steps to compile the sample script: 1. Load the modules: 1 2

% module load matlab %module load gcc/4.7.3 # or later

2. If this is the first time you are using MATLAB to create an executable, run: 1 2 3

%matlab -nodisplay >>mbuild -setup >>exit

3. Compile the script into an executable. At the Linux or MATLAB prompt, run: 1

%mcc -m findR.m -o findR

CALLING OBJECTS FROM EXTERNAL PROGRAMS

55

Two records are made: An executable: findR A shell content: run_findR.sh To run the executable, add the accompanying lines to your PBS content or run them at the Linux incite: 1 2 3

%module load matlab/2016b %module load gcc/4.7.3 ./run_findR.sh $MATLAB

The output will be: 1 2 3 4 5 6 7

% ./run_findR.sh $MATLAB %------------------------------------------------------------------% Setting up environmental variables %------------------------------------------------------------------LD_LIBRARY_PATH is ./your path R = Value

2.10

Calling Objects from External Programs

The Microsoft Component Object Model (COM) gives a structure to planning parallel programming parts into an application. Since these parts are completed in accordance with the organized code, those code are created by programming vernaculars which provide assistance Component Object Model. Table 2.9

Calling objects functions.

actxserver

Create a COM server

actxcontrol

Create Microsoft ActiveX control in the figure window

actxcontrollist

List currently installed Microsoft ActiveX controls

actxcontrolselect

Create Microsoft ActiveX control from UI

eventlisteners

List event handler functions associated with COM object events

methodsview

View class methods

registerevent

The associated event handler for COM object event at run time

unregisterallevents

Unregister all event handlers related to COM object events

unregisterevent

Unregister event handler associated with COM object event at run time

iscom

Determine whether the input is COM or ActiveX object

isevent

Determine whether the information is COM object event

isinterface

Determine whether the information is COM interface

56

INTRODUCTION TO MATLAB PROGRAMMING

2.11

JAVA Classes

You can access existing Java classes to use in the MATLAB workspace. For example, built-in class packs, such as java.util, can be used, which are included in the Java lingo. See your Java vernacular documentation for delineations of these packs. Furthermore, you can access classes described in solitary class reports, packages, or Java archive (JAR) records, including types you create. 4

Table 2.10 import

Java class functions.

Add package or class to current import list

isjava

Determine if the input is Java object

javaaddpath

Add entries to dynamic Java class path

javaArray

Construct Java array object

javachk

Error message based on Java feature support

javaclasspath

Return Java class path or specify the dynamic path

javaMethod

Call Java method

javaMethodEDT

Call Java method from Event Dispatch Thread (EDT)

javaObject

Call Java constructor

javaObjectEDT

Call Java constructor on Event Dispatch Thread (EDT)

javarmpath

Remove entries from dynamic Java class path

usejava

Determine if Java feature is available

Capture error information for Java exception: matlab.exception.JavaException

2.12

The Guide

This case exhibits and makes use of a GUIDE to create an application. The following zones guide you through the route toward making this application. In case you need to oversee as well as execute the code, create the current envelope [6]. CODE: 1 2 3 4

copyfile(fullfile(docroot, ’techdoc’, ’creating_guis’))... ’examples’, ’simple_gui*.*’)), fileattrib(’simple_gui*.*’, ’+w’); control ’simple_gui.fig’; alter simple_gui.m

OUTPUT 4 https://www.tutorialspoint.com/java/java

exceptions.htm

THE GUIDE

2.12.1

Open a New User Interface

Step 1- Initiate the GUIDE by composing GUIDE at inciting.

Step 2 - In GUIDE Blank GUI (Default) template OK.

Step 3 - Display the names of the parts in the segment palette: Select File\Preferences\Guide Select Show names in part palette. Click OK.

57

58

INTRODUCTION TO MATLAB PROGRAMMING

2.12.2

Guide Window Size Setting

Set the size of the user interface window by resizing the grid area in the layout editor. Click the lower-right corner of the layout area and drag it until the user interface is the desired size.

2.12.3

Design the User Interface

Include, adjust, as well as mark the parts in the User Interface. Create three push buttons in the User Interface.

THE GUIDE

59

Create rest of the segments to the User Interface – A static content territory – A pop-up menu – A tomahawk Organize sections according to the figure. Resize the tomahawks part roughly two-by-two inches.

2.12.4

Adjust the Components

In the event that a few fragments have a comparable parent, the Alignment Tool is used to change them to each other. Choose each of the three push buttons catches and press Ctrl to monitor. Choose Tools is higher than Aligning Objects. Left-adjusted in the level course. Twenty pixels are dispersed among push button catches in the vertical bearing.

60

INTRODUCTION TO MATLAB PROGRAMMING

Give OK.

2.12.5

Mark the Push Buttons

Every push catch indicates a plot to compose: surf, work, as well as form. Here, the segment demonstrates the best practices for marking traps with alternatives. 1. Choose View is higher than the Property Inspector.

2. Layout area -> top push button.

3. Property Inspector -> String property replaces with Surf.

4. Give ENTER. Then you can see that the push button looks the same as Surf. Then follow the same procedure to change the second push button to Mesh and third push button to Contour.

THE GUIDE

2.12.6

61

Menu Items-Rundown Pop-Up

Step 1 - Pop-up menu Item gives you an option for three instructive accumulations, which are primarily zeniths, secondly layer, and finally sinc. By using a comparable name, we can identify the MATLAB components in the enlightening lists. This section presents a widely recognized technique which can be listed to those instructive accumulations as a pop-up menu option. Step 2 - Go to Property Inspector, catch String. You can get the String talk box.

Step 3 - Delete the old content and type the new content peaks, membrane, and sinc. Give OK.

Step 4 - Peaks is the first items which we have given as an input, which will then appear first in the pop-up menu.

2.12.7

Static Test Alteration Procedure in MATLAB

Step 1 - In this User Interface (UI), the static substance gives a name for the pop-up menu in MATLAB. Those regions provide us legitimate philosophies to modify the test substance to examine Select Data.

62

INTRODUCTION TO MATLAB PROGRAMMING

Step 2 - From the format region, select the static content, and go to the Property Inspector, tap catch by String option. There supplant present substance by articulation Select Data.

Step 3 - Then Give OK. Now you can see that the term Select Data is displayed in the static text component, which is present in the upper portion of the pop-up menu.

2.12.8

Spare the Layout

While saving the configuration, GUIDE makes two types of records, the first one is a FIG-archive record and the second one is a code record. In the case of code record, which is represented in the file format of .m, MATLAB employs limits which are used to monitor the applications. Step 1 - Save it, then run it by picking (Tools > Run). Step 2 - GUIDE introductions talk-box appearing: It will initially save the changes which are present in the figure and also in the MATLAB program. In case you need to continue answer Yes. Step 3 - Then GUIDE shows a Save As option and gives a FIG-report name. Step 4 - Here you can browse any envelope to take benefits, and then give the file name as simple_gui, which is the graphical user interface for the FIGrecord. Then GUIDE will automatically save all the details in the given name only in the future.

THE GUIDE

63

Step 5 - Use the envelope to save the report. GUIDE provides an option to change the present coordinator in the talk box. Step 6 - GUIDE recovers records in both the .fig file and the .m file, and a while later runs the code. Then it opens the program record in the editor. Here we will get another window. There is no menu bar and toolbar. In this situation, we have to create our menu bars and toolbars, which is usually done for a GUIDE application.

Figure 2.10

Inspecting MATLAB GUI.

There is a procedure which can run the application without opening the GUIDE, by typing the file name we can run it. Here run command can also be used to run the code 1

Command - run simple_gui

2.12.9

Behavior of the App

While saving the program in a past zone, first we have to save the Layout; here GUIDE provides two archives which are FIG-record and program record. We created the FIG-record file as simple_gui.fig, and the program record file is named simple_gui.m. In any case, the application isn’t authorizing because simple_gui.m doesn’t hold any declarations which can be used to do exercises. This part shows the appropriate procedure to insert code to record and to create a useful application. 2.12.10

Produce Data to Plot in MATLAB

The fragment provides many acknowledged strategies to create data and plot it at the time when the customer clicks catch. The starting limit creates the data by MATLAB

64

INTRODUCTION TO MATLAB PROGRAMMING

limits calling function. Starting limit presents User Interface when it gets started, which is essential for every GUIDE-made code archive process. For these kinds of situations, we can incorporate code which makes three educational records to the opening limit. These limits are apexes, film, and sinc. Step 1 - MATLAB Editor will display the opening limits. In this case record, the .m file doesn’t start when it is opened in the administrator, but it is opened from the Layout Editor by picking the great condition View > Editor. Step 2 - EDITOR tab -> NAVIGATE territory -> click Go To, then after -> choose simple_gui_OpeningFcn. The code is present in the opening limit, and the cursor moves there: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

%--------------Executes just before simple_gis made visible-------Function simple_gui_OpeningFcn(hObject,event data,handles,varargin) %This function has no output args, see OutputFcn %hObject handle on figuring %eventdata reserved - to be defined in a figure version of MATLAB %handles structure with handles and user data (see GUIDATA) %varargin command line arguments to simple_g(see VARARGIN) %------------------------------------------------------------------%Choose default command line output for simple_gui Handles.output = hObject; %Update Handles Structure Guidata((hObject, handles); %UIWAIT makes simple_gwait for user response (see UIRESUME) %uiwait(handles.figure1);

By adding the code given below, we can create the data to plot in the opening function after the line starts with the symbol (%) varargin... CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14

%------------------------------------------------------------------%Create the data to plot. %------------------------------------------------------------------Handle.peaks = peakes(35); Handles.membrane = membrane; [X,Y] = meshgrid(-8:.5:8); R = sqrt(x.ˆ2+y.ˆ2) + eps; Sinc = sin(r) ./r; Handles.sinc= sinc; %------------------------------------------------------------------% set the current data value %------------------------------------------------------------------Handles.current_data = handle.peaks; Surf(handles.current_data)

These codes make use of the MATLAB limits apexes, layer, and sinc. Here the handles structure will store the data. This helps to recover data from handles structure.

THE GUIDE

Figure 2.11

2.12.11

65

Simple GUI.

Pop-Up Menu Characteristics

Step 1 - Fly-up menu bar provides decisions on data plotting. Precisely, the client picks three plots. Step 2 - MATLAB Editor shows the pop-up menu callback. Step 3 - GUIDE Layout shown below.

Figure 2.12

Selecting callback options.

GUIDE PROCEDURE 1 2 3 4 5 6

GUIDE demonstrates the code record in the editor and moves the cursor to the pop-x callback, which contains this code: %------------------------------------------------------------------%- Executes on assurance change in popupmenu1 %------------------------------------------------------------------Work popupmenu1_Callback(hObject, eventdata, handles)

66 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

INTRODUCTION TO MATLAB PROGRAMMING

%------------------------------------------------------------------%hobject handle to popupmenu1 (see GCBO) %eventdata held -to be described in a future adjustment of MATLAB %handles structure with handles and customer data(see GUIDATA) %------------------------------------------------------------------Add the going with the code to the popupmenu_Callback after the comment that begins handles This code at first recoups two flies up menu properties: .String-a telephone show that contains the menu substance .Value-the record into the menu substance of the picked enlightening accumulation The code by then uses a change explanation to make the picked instructive gathering present data. The last decree saves the movements to the handles structure. %------------------------------------------------------------------%Determine the chose informational collection. %------------------------------------------------------------------Str=get(hObject,’String’); Val =get(hObject,’Value’); %------------------------------------------------------------------%Set current information to the chose informational index. %------------------------------------------------------------------Switch str{val}; %User chooses tops. Case ’crests; Handles.current data=handles.peaks; %User chooses layer. Case ’film’ Handles.current data=handles.membrane; %User chooses sinc. Case ’sinc’ Handles.current data=handles.sinc; End %Save the handles structure. Guidata(hObject.handles)

2.12.12

Behavior of Push Button

Every push button gets substitute kind of plot using information demonstrated with the help of the present decision in the pop-up menu. The handles structure provides the callbacks to the push button, after that they are ready to plot. Surf button gets callback right-tap Surf push, later View Callbacks -> Callback. PROCEDURE 1 2 3 4 5 6

In the Editor, the cursor moves to the Surf push catch callback in the code document, which contains this code: %------------------------------------------------------------------%-Executes on catch press in pushbutton1. %------------------------------------------------------------------Function pushbutton1_Callback(hObject,eventdata,handles)

EFFECTIVE PROGRAMMING THROUGH MATLAB

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

67

%hObjectbhandle to pushbutton1(see GCBO) %eventdata saved-to be characterized in a future variant of MATLAB %handles structure with handles and client information (see GUIDATA) Add the accompanying code to the callback instantly after the remark that starts %handles %------------------------------------------------------------------%Display surf plot of the as of now chose information. %------------------------------------------------------------------Surf(handles.current data); Rehash stages 1 and 2 to add comparable code to the Mesh and Contour push catch callbacks. .Add this code to the Mesh push catch callback, pushbutton2_Callback: %------------------------------------------------------------------%Display work plot of the at present chosen information. %------------------------------------------------------------------Mesh(handles.current data); Add this code to the Contour push catch callback, pushbutton3_Callback: %------------------------------------------------------------------%Display shape plot of the as of now chose information. %------------------------------------------------------------------Sparse your code by choosing File>Save.

Figure 2.13

2.13

Selecting callback options 2.

Effective Programming through MATLAB

Strategies to Improve the Performance in MATLAB. To increase the speed of execution of the system, the following conditions are used.

68

INTRODUCTION TO MATLAB PROGRAMMING

2.13.1

Condition

Think about establishing frames that offer computational resources as well as which help to reduce the execution time of the code. Code Structure: Step 1 - Utilize works as opposed to substance. Limits are all things considered speedier. Step 2 - Prefer adjacent limits over settled limits. Utilize this kind of preparation particularly in the case where the boundaries are not responsible for the factors in the essential limit. Step 3 - Utilize disconnected programming to create a useful programming model in MATLAB. This type of preparation is used to reduce running costs. 2.13.2

Practice Programs

This method of practice programs is used to improvise the execution of the program. Step 1 - Pre-allocation – Rather than reliably dynamic sizing displays, think about pre-allocation of most proportions with the room needed for a group. For the required additional information, you can look at Pre-allocation. Step 2 - Vectorize – Rather than creating a circular structure of the program, think about the MATLAB system as well as vector assignments. When additional information is required, you can look at Vectorization. Step 3 - Place free undertakings out of the coverage area of the circles – In case the code fails to survey with some other route with each circle accentuation, shift it out of the hover to reduce the redundant computations. Step 4 - Build newer factors while data gets modified – Build another variable as opposed to consigning data of a substitute sort to a present variable. By changing the class or display condition of a current variable, it gives additional chance to process. Step 5 - Use cut off – Use short-circuiting true-blue heads, && and ||, when possible. Short circuiting is more capable in light of the way that MATLAB surveys the second operand precisely when the fundamental operands are not managing the results. For required additional information, you can look at Logical Operators: Short Circuit. Step 6 - Stay away from overall components – The usage of global elements has to be minimized to get the standard programming practices. Also, the global variable can lessen execution. Step 7 - Stay away from overloading amassed ins – Stay away from overcomplicated works which limit data classes.

CLONES PROCESS USING MATLAB

69

Step 8 - Stay away from the usage of “data as code” – In a case where you can provide free parts of code (e.g., more than 500 lines) which create factors among steady characteristics, think about building the variables as well as saving them in MATLAB-record. Now, instead of execution, we can use the stack option to generate them. 2.13.3

Specific Functions in MATLAB

There are specific MATLAB limits when executing the first program. Step 1 - Stay away from clearance of a maximum number of code that would regularly be fitting. Do whatever it takes not to make use of clear all. For required additional information, you can look at clear. Step 2 - Stay away from limits in the inquiry domain; the ideology of runtime is computationally costly. Step 3 - Stay away from limits for instance, and eval. Utilize limit handle commitment to feval at whatever point promising. Step 4 - Stay away from programmed usage of the conservative circle, (addpath), as well as (rmpath), at the time of suitable situations. Modifying the path during runtime results in code recompilation.

2.14

Clones Process Using MATLAB

For a few areas in number-theory, material sciences, architecture, financial sectors, and the unique regions including high-dimensional numeric portion, the introduction to program considered by using MATLAB. Nevertheless, MATLAB is one of the select instruments. Here you can get understanding and modification process of the code without accessing the source code. These are the essential factors of the cloning process using MATLAB. 2.14.1

GNU Octave

Another choice preferred by MATLAB is GNU Octave. It has been an excellent change for pretty much three decades; GNU Octave continues running on Windows operating system, Mac operating system, and Linux operating system as well as being used mostly in several genuine allotments. If you’re searching for an endeavor which is nearer to authentic MATLAB lingo, GNU Octave is a possible active counterpart in general; since it tries rectification likeness, tremendous quantities of your undertakings made for MATLAB can also continue running in GNU Octave without alteration, making it indispensable. GNU Octave consists of an extensive variety of choices open for a front-end association by conveys with frame 4; some take after MATLAB’s interface more than

70

INTRODUCTION TO MATLAB PROGRAMMING

the other software. GNU Octave’s Wikipedia page records a couple of options. GNU Octave got approval in GPL, and you can also get the codes about this concept on the GNU FTP site. 2.14.2

Scilab

Scilab is another open source software elective in favor of numerical assuming which continues running over every critical stage: Windows operating system, Mac operating system, and Linux operating systems are incorporated. It is in a general sense the same as MATLAB in its use, improve the proximity isn’t a target of the endeavor’s specialists [20]. Scilab got approval in GPL, and you can also get the codes about this concept in the assignment site. 2.14.3

Sage

Sage is another open source number juggling programming method and is a better than average choice for those searching for a MATLAB elective. It’s based on a combination of known Python-based sensible enrolling libraries and provides its particular language which is parallel with Python concepts. It consists of various features which bring together line interface, program diaries, gadgets used for embedding in multiple files, and, obviously, various numerical libraries. It got approval in GPL, and you can also get the codes concerning this concept on the Endeavor site. Here we present details about some other open source instruments which you may need to consider: FreeMat5 is one of the open source software and GPL-approved condition for outlining legitimate prototyping. This package can be operated in the Linux operating system and Microsoft’s operating system OS X and Windows. The latest version of this software was released in 2013. Genius Mathematics Tool6 is one of the open source software, a viably made small-scale PC program, and research instrument. The language which is used for Genius Mathematics Tool is Genius Extension Language. This package can be operated in the Linux operating system and Unix Personal Computers. Maxima7 is one of the open source software, which is most frequently used as a most differentiating alternative to MATLAB. It relies upon Macsyma, a “stunning PC polynomial math structure” developed at MIT in the 1960s. This package can be operated in the Linux operating system, and Microsoft’s operating system OS X and Windows. 5 www.freemat.info/ 6 https://www.linuxlinks.com/genius/ 7 maxima.sourceforge.net/

PARALLEL MATLAB SYSTEM

71

NumPy8 is one of the open source software with a package that includes a maximum number of the features of Python. It acts as an essential key for SciPy Stack; its package consists of math, science, and building programming-based Python concepts. NumPy got approval from BSD. This package can be operated in the Linux operating system, and Microsoft’s operating system OS X and Windows. SymPy9 is one of the open source software which was approved by BSD for an exact science. It is intended for use in all types of PCs running Python version 2.7 or above. It intends to finish PC polynomial math system; has a working change connect with precise releases; and is used in various diverse errands (checking SageMath, above). 2.15 2.15.1

Parallel MATLAB System Run a Batch Job

This case uses the for-hover from the past case, inside a substance [13, 14]. 1. To create the script, type: 1

edit mywave

2. In the MATLAB Editor, enter the text of the for-loop: 1 2 3

for i=1:1024 A(i)=sin(*2*pi/1024); end

3. Save the record and close the Editor. 4. Use the cluster order in the MATLAB Command Window to run your content on a different MATLAB specialist: 1

job=batch(’mywave’)

5. The cluster summons does not square MATLAB, so you should sit tight for the activity to complete before you can recover and see its outcomes: 8 https://www.numpy.org/ 9 https://www.sympy.org/

72

INTRODUCTION TO MATLAB PROGRAMMING

1

wait(job)

6. The heap charge exchanges factors made on the laborer to the customer workspace, where you can see the outcomes: 1 2

load(job,’A’) plot(A)

7. When the job is complete, permanently delete its data and remove its reference from the workspace: 1 2

delete(job) clear job

Batch runs your code on a local worker or a cluster worker, but does not require a parallel pool. You can use batch to run either scripts or functions. For more details, see the batch reference page. 2.15.2

Run a Batch Parallel Loop

You can enhance the abilities to offload employment and run a parallel circle. In the previous two representations, you balanced a for-hover to make a parfor-circle, and you have referenced a for-hover as group work. This case merges the two to make a bunch parfor-circle [15, 16]. 1. Open your content in the MATLAB Editor, to create a script, type: 1

edit mywave

2. Adjust the content so that the explanation is a part for articulation: 1 2 3

parfor i=1:1024 A(i)=sin(i*2*pi/1024); end

3. Save the file and close the Editor. 4. Run the content in MATLAB with the bunch summon as previously, yet demonstrate that the content should utilize a parallel pool for the circle: 1

job=batch(’mywave’,’pool’,3)

This charge demonstrates that three workers (despite the one running the gathering content) are to evaluate the circle cycles. Subsequently, this case uses all four adjacent workers, including the one authority running the group content. There are five MATLAB sessions required, as shown in the following diagram.

PARALLEL MATLAB SYSTEM

73

5. To view the results: 1 2 3

wait(job) load(job,’A’) plot(A)

The results look the same as before. However, there are two essential differences in execution:

The work of portraying the parfor circle and assembling its results are offloaded to another MATLAB session by the cluster. The circle cycles are scattered beginning with one MATLAB master then onto the following plan of workers running at the same time (’Pool’ and parfor), so the circle may run faster than when having only a solitary pro execute it.

6. When the job is complete, permanently delete its data and remove its reference from the workspace: 1 2

2.15.3

delete(job) clear job

Current Folder Browser - Run Script as Batch Job

Pack work continues running on the gathering recognized by the default bundle profile. The going with figure exhibits the different menu option to run the substance record script1.m:

74

INTRODUCTION TO MATLAB PROGRAMMING

Figure 2.14

Running script as batch job.

Running a substance as a cluster from the program uses only a solitary pro from the gathering. So, paying little mind to whether the substance contains a parfor circle or spmd square, it doesn’t open a new pool of experts on the pack. These code squares execute on the single master used for the group work. If your cluster content requires opening a new pool of experts, you can run it from the call line, as delineated in Run a Batch Parallel Loop. When you run a gathering work from the program, this opens the Job Monitor. The Job Monitor is an instrument that allows you to track your movement in the scheduler line. For more information about the Job Monitor and its abilities, see Job Monitor.

2.16

Conclusion

The main motto of the chapter is to maintain the consistency of the technology distribution of the network using MATLAB and the syntax implementations of MATLAB. This chapter dealt with the explanation of different syntax formats of MATLAB and its different features. Different formats and notations are explained which will be helpful for understanding MATLAB implementation in network simulation. Simulation is used to understand the importance of import and export operations and other simple scenarios which we need to consider while learning the network operations. All these scenarios are explained in this chapter and the important elements of MATLAB, including with basics, are also explained. Students can get complete knowledge on the subject along with the basics of network modeling with MATLAB.

CONCLUSION

75

REFERENCES 1. Kharab, A., & Guenther, R. (2018). An introduction to numerical methods: a MATLAB approach. CRC Press. 2. Martinez, W. L., & Martinez, A. R. (2007). Computational statistics handbook with MATLAB. Chapman and Hall/CRC. 3. Moore, H. (2017). MATLAB for Engineers. Pearson. 4. Schmidt, J. D. (2010, July). Numerical simulation of optical wave propagation with examples in MATLAB. Bellingham, Washington, USA: SPIE. 5. Hanselman, D. C., & Littlefield, B. (2005). Mastering Matlab 7. Pearson/Prentice Hall. 6. Holland, O. T., & Marchand, P. (2002). Graphics and GUIs with MATLAB. Chapman and Hall/CRC. 7. Smith, D. M. (2010). Engineering Computation with MATLAB. Boston: Addison/Wesley, 8. Quinquis, A. (2008). Digital signal processing using MATLAB. Wiley-IEEE Press. 9. Messner, W. C., Tilbury, D. M., & Hill, A. P. R. (1999). Control Tutorials for MATLAB and Simulink. 10. Herniter, M. E. (2000). Programming in MATLAB. Brooks/Cole Publishing Co. 11. Choy, R., & Edelman, A. (2005). Parallel MATLAB: Doing it right. Proceedings of the IEEE, 93(2), 331-341. 12. Trefethen, A. E., Menon, V. S., Chang, C. C., Czajkowski, G., Myers, C., & Trefethen, L. N. (1996). MultiMATLAB: MATLAB on multiple processors. Cornell University. 13. Travinin Bliss, N., & Kepner, J. (2007). pMATLAB Parallel MATLAB Library. The International Journal of High Performance Computing Applications, 21(3), 336-359. 14. Kepner, J., & Travinin, N. (2003). Parallel MATLAB: The next generation. MASSACHUSETTS INST OF TECH LEXINGTON LINCOLN LAB. 15. Choy, R., & Edelman, A. (2003). Matlab* P 2.0: a unified parallel MATLAB. 16. Bulej, V., Urek, J., Eberth, M., Kuric, I., & Stanek, J. (2019). Modelling and Simulation of Machine Tool Prototype with 6DOF Parallel Mechanism in Matlab/Simulink. In MATEC Web of Conferences (Vol. 254, p. 03002). EDP Sciences. 17. Luszczek, P. (2009). Parallel programming in MATLAB. The International Journal of High Performance Computing Applications, 23(3), 277-283. 18. https://www.mathworks.com/ 19. https://www.tutorialspoint.com/matlab/matlab overview.htm 20. https://en.wikipedia.org/wiki/Scilab

CHAPTER 3

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Abstract In this chapter, we explain how digital communication system simulations can be performed using MATLAB. We provide a detailed introduction to digital communications, i.e., data transmission with example. Next, a detailed explanation is given of simulation of Rayleigh Fading Model, BPSK modulation and demodulation, QPSK modulation and demodulation along with their MATLAB coding and show the output as well. We also explain Image Error Rate vs Signal-to-Noise Ratio and OFDM with sample MATLAB coding and their productions. Keywords: Digital communication, Rayleigh fading model, BPSK, QPSK, image error rate, signal-to-noise, OFDM framework

Network Modeling, Simulation and Analysis in MATLAB. c 2019 Scrivener Publishing By Dac-Nhuong Le et al. Copyright 

77

78

3.1

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Introduction to Digital Communication

Transmitting information in discrete messages takes into account more prominent signal handling capacity. The capacity to process an interchange signal implies that mistakes caused by uneven rules are distinguished as well as solved. Advanced signs are otherwise tested sooner and continuously observed, and different symbols are multiplexed mutually for shaping signal. Here is an outline of what will be covered in this chapter. 1. Information Transmission: Channel qualities, signaling techniques, obstruction and commotion, and synchronization; 2. Data Sources and Coding: Information hypothesis, coding of data for productivity and error security encryption; 3. Signal Representation: Representation of discrete time motions in time and recurrence, z-change and Fourier transformations, the distinct estimate of constant signs, examining and quantization and information pressure; 4. Sifting: Analysis and combination of separate time channels; limited motivation reaction and interminable drive reaction channels, recurrence reaction of digital channels, shafts, and zeros, channels for connection and identification, coordinated channels and stochastic signals and clamor forms; 5. Computerized Signal Processing Applications: Processing of pictures utilizing advanced procedures [1, 2]. The utilization of DCSP in industry and our day-to-day life is enormous, even though in this basic module we are just ready to address a few straightforward cases. Many thanks go to Dr. Enrico Rossoni, who has invested an impressive amount of energy in looking over the original copy a few times to amend the grammatical errors. The incorporated segments are just for one’s reference [3, 7, 9]. 3.1.1

Data Transmission

A correspondences framework is in charge of the transmission of data from the sender to the beneficiary. At its least complex, the frame contains (see Figure 3.1):

Figure 3.1

Data transmission system.

INTRODUCTION TO DIGITAL COMMUNICATION

79

1. For physically proper transmission channel, a modulator that takes the source signal and changes it. 2. A transmission channel that is the physical association passing between the parties. 3. A transmitter that genuinely carries the adjusted signal into the channel, generally speaking, opening up the signal as it does all things being considered. 4. A recipient that perceives the transmitted signal on the circuit and as a general rule strengthens it (as its track will have debilitated it through the channel). From the signal received, a demodulator gets the first source motion and passes it to the sink. At each stage, signal handling procedures are required to distinguish signals, sift through the commotion and concentrate highlights, as will be examined in the second part of the chapter. Advanced information is spoken to in all respects by a series of 1s or 0s. Every one or zero is alluded to as a bit. Regularly, yet not generally, these bit strings are translated as numbers in a parallel number framework. In this way, (1010012 = 4110 ), the data substance of a computerized signal is equivalent to the number of bits required to speak to it. Along these lines, a signal that may change somewhere in the range of 0 and 7 has a data substance of 3 bits. Composed as a condition this relationship is I = log2 (n) bits (3.1) where n is the number of levels a signal may take. Note that data is a proportion of the number of different results taken. The data rate is a proportion of the speed with which data is exchanged. It is estimated in bits/second or b/s. 3.1.2

Example

Media communications movement is described by incredible decent variety. A nonrestrictive rundown is given below:

Figure 3.2

Time domain and frequency domain representation of a signal.

80

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

1. Sound signs: A sound signal is a case of a simple signal. It involves a recurrence extending from around 200 Hz to around 15 KHz. Discourse signals possess a small range of frequencies, and phone discourse normally involves the range of 300 Hz to 3300 Hz. The range of frequencies involved by the signal is called its data transmission (see Figure 3.2); 2. TV flag: A TV signal is a simple signal made by checking a two-dimensional picture. Ordinarily, the signal possesses a transfer speed of around 6 MHz; 3. Tele-text is composed (or drawn) interchanges that are deciphered outwardly. Wire portrays a message restricted to a foreordained arrangement of alphanumeric characters; 4. Repeating cells, in which the child cells’ DNA contains data from the parent cells; 5. Circle drives; 6. Our cerebrum. The utilization of computerized signs and adjustment has excellent points of interest over simple frameworks. These are: 1. High constancy. The discrete idea of digital signals makes their qualification within sight of commotion simple. High loyalty transmission and description are conceivable. 2. Time autonomy. A digitized signal is a flood of numbers. Once digitized a signal might be transmitted at a rate detached with its chronicle rate. 3. Source autonomy. The computerized signs might be transmitted utilizing a similar arrangement independent of the wellspring of the correspondence. Voice, video, and content might be sent using the same channel. 4. Signs might be coded. The same transmitted message has an endless number of implications as per the lead used to translate it. One load of electronic correspondence is the expanded cost of transmitters and recipients. This is especially valid for continuous communication of simple signs. 3.1.3

The Conversion of Analog and Digital Signals

With a specific end goal to send simple signals over a computerized correspondence framework, or process them on an advanced PC, we have to change over simple signs to advanced ones. This procedure is performed by a simple-to-advanced converter (ADC). The simple signal is inspected (i.e., estimated at the frequently dispersed moment) (Figure 3.3) and after that quantized (Figure 3.4, a baseboard), i.e., changed over to discrete numeric qualities. The different activity to the ADC is performed by

INTRODUCTION TO DIGITAL COMMUNICATION

81

a computerized-to-simple converter (DAC). A vital law represents the ADC procedure [8, 13-15].

Figure 3.3

Analog-to-digital conversion.

The Nyquist-Shannon Theorem expresses that a simple signal of transfer speed B can be reproduced from its examined shape tests at a rate equivalent to no less than twice its transmission capacity. That is S ≥ 2B

(3.2)

The rate at which an ADC creates bits relies upon what number of bits is utilized in the converter. For instance, a discourse signal has an estimated transfer speed of 4 KHz. On the off chance that this is examined as 8-bit ADC at Nyquist testing rate, where R is given as the bit rate to change the signal without loss of data R = 8 bits × 2B = 64000 b/s

(3.3)

Figure 3.4 Upper panel: Periodic sampling of an analog signal. Bottom panel: Quantization of a sampled signal.

82

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

3.1.4

Information, Bandwidth, and Noise

One of the critical inquiries related to the correspondence channel provides the greatest rate for data exchange. Simple signals going through physical channels may not accomplish self-assertively quick changes. The data transmission dictates the rate at which a signal may change. To be specific, a signal of transfer speed B may change at a most extreme rate of 2B, so the highest data rate is 2B. On the off chance that progressions of contrasting greatness are each related to a different piece, the data rate might be expanded [6]. In this way, if each time the signal transforms, it can take one of the n levels, the data rate is extended to R = 2Blog2 (n) b/s

(3.4)

This equation expresses that as n watches out for vastness, so does the data rate. Is there a point of confinement on the number of levels? The nearness of clamor sets the farthest point. On the off chance that we keep on subdividing the size of the progressions into regularly diminishing interims, we achieve a point that can’t recognize entity levels due to the nearness of commotion. Commotion hence puts a breaking point on the most extreme rate data exchange. Here the true matters are the signal clamor proportion. This type of concept is characterized by proportion signal control S which can clamor control N, which is frequently communicated in decibels (dB):   S dB (3.5) SN R = 10log10 N The wellspring of commotion signals changes broadly: 1. Info commotion is regular in low recurrence circuits and emerges from electric fields created by electrical exchanging. It shows up as blasts at the recipient, and when present can have a disastrous impact because of its huge power. Other individuals’ signs can produce commotion: crosstalk is the term surrendered to the pick of emanated signals from nearby cabling. At the point when radio connections are utilized, obstruction from different transmitters can be hazardous. 2. Warm commotion is continuously present. This is because of the arbitrary movement electric charges exhibit in all media. It tends to be produced remotely, or inside at the collector. The most extreme hypothetical to the rate at which the data disregards errors is not considered in a channel. It is known as the channel limit. Here, the well-known Hartley-Shannon Law says the channel limit, C, is given below   S C = Blog2 1 + bps (3.6) N Here, a 10 KHz channel works in a signal-to-noise ratio of 15 dB and hypothetically has the most extreme data rate of 10000log2 (31.623) = 49828 b/s. The hypothesis puts forth no expression concerning how the channel limit is accomplished. Practically speaking, channels approach this farthest point. The undertaking of giving high channel productivity is the objective of coding procedures.

SIMULATION OF RAYLEIGH FADING MODEL

3.2

83

Simulation of Rayleigh Fading Model

Rayleigh fading is the name given to the type of fading that is frequently experienced in a situation where there is an expansive number of reflections display. The Rayleigh fading model uses a measurable way to deal with examining the spread and can be utilized in various situations. The Rayleigh fading model is regularly seen as a reasonable way to deal with taking when breaking down and forecasting radio wave proliferation execution for zones; for example, cell correspondences in a well-developed urban condition where there are many reflections from structures, and so on. HF ionospheric radio wave spread where reflections (or all the more precisely refractions) happen at numerous focuses inside the ionosphere is likewise another territory where Rayleigh fading model applies well. It is additionally fitting to utilize the Rayleigh fading model for tropospheric radio engendering because again there are many reflection points and the signal may take after a wide range of ways. The Rayleigh fading model is most pertinent to events where there is a wide range of signal ways, none of which are prevailing. Along these lines, all the signal ways will shift and can affect the general signal at the recipient [7].

3.2.1

Rayleigh Fading Basics

The Rayleigh Fading model is especially valuable in situations where the signal might be thought to be scattered between the transmitter and collector. In this type of situation, no single signal way overwhelms and a measurable approach is required for the examination of the general idea of the radio interchanges channel. Rayleigh fading is a model that can be utilized to portray the type of fading that happens when multipath spread exists. In any earthly condition, a radio signal will travel using various diverse ways from the transmitter to the collector. The most precise method is the direct or viewable pathway way. As there is frequent development of the transmitter or the beneficiary, this can make the way lengths change and the signal level will shift as needed. Moreover, if any of the items being utilized for reflection or refraction of any piece of the signal moves, at that point this too will cause variety. This happens because a portion of the way lengths will change and this will mean their relative stages will change, offering ascent to an adjustment in the summation of all the received signals. The Rayleigh fading model can be utilized to dissect radio signal proliferation on a factual premise. It works best under conditions when there is no common sign (e.g., coordinate viewable pathway signal), and in numerous events cell phones being utilized in a thick urban condition fall into this classification. Several cases where no overwhelming way by and large exists are for ionospheric engendering where the signal achieves the recipient using an immense number of individual styles. Spread utilizing tropospheric ducting likewise displays similar examples. In like manner, every one of these cases is perfect for the utilization of the Rayleigh fading or engendering model.

84

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

3.2.2

Rayleigh Fading

The deferrals related to various signal ways in a multipath fading divert change in an unusual way and must be described factually. Right when there is a large number of courses, beyond what many would consider possible speculation can be associated with showing the time-variety inspiration response of the channel as a complexregarded Gaussian discretionary process. At the point when the motivation reaction is demonstrated as a zero-mean complex-esteemed Gaussian process, the channel is said to be a Rayleigh fading channel [8]. The model behind Rician fading is like that for Rayleigh fading, with the exception that in Rician fading a prevailing stable segment is available. This overwhelming part can, for example, be the observable pathway wave. For our situation, the Rayleigh Fading model is expected to have just two multipath parts, X(t) and Y (t). Rayleigh Fading can be acquired from zero-mean complex Gaussian procedures (X(t) and Y (t)). Essentially, including the two Gaussian Random factors and taking the square root (envelope) gives a Rayleigh appropriated process. The stage takes after uniform conveyance. MATLAB Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

%-----------------------Input Section-----------------------------%Number of samples to generate N=1000000; % Variance of underlying Gaussian random variables Variance = 0.2; %------------------------------------------------------------------% Independent Gaussian random variables with zero mean and % unit variance %------------------------------------------------------------------X=randn(1,N); Y=randn(1,N); %------------------------------------------------------------------%rayleigh fading envelope with the desired variance %------------------------------------------------------------------R=sqrt(variance*(x.ˆ2+y.ˆ2)); %define bin steps and range for histogram plotting Step=0.1; range=0:step:3; %------------------------------------------------------------------%get histogram values and approximate it to get the pdf curve %------------------------------------------------------------------H=hist(r,range); %simulated PDF from the x and y samples approxPDF=h/(step*sum(h)); %------------------------------------------------------------------%Theoritical PdF from the Rayleigh fading equation %------------------------------------------------------------------Theoretical=(range/variance).*exp(-range.ˆ2/(2*variance)); Plot(range,approxPDF,’b*’,range,theoretical ,’r’); Title(’Simulation and theoretical rayleyigh PDF for variance=0.5’) Legend(’simulated PDF’,’theoretical PDF’) Xlabel(’r ->’);

SIMULATION OF RAYLEIGH FADING MODEL

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

85

Ylabel(’p(r)->’); Grid; %------------------------------------------------------------------%PdF of phase of the Rayleigh envelope %------------------------------------------------------------------Theta=atan(y./x); Figure(2) %plot histogram of the phase part Hist(theta); %------------------------------------------------------------------%approximate the histogram of the phase part to a nice PDF curve %------------------------------------------------------------------[counts,range]=hist(theta,100); Step=range(2)-range(1); approxPDF=counts/(step*sum(counts)); %------------------------------------------------------------------%simulated PDF from the x and y samples %------------------------------------------------------------------bar(range,approxPDF,’b’); hold on plotHandle=plot(range,approxPDF,’r’); set(plotHandle,’LineWidth’,3.5); axis([-2 2 0 max(approxPDF)+0.2]) hold off title(’simulatedd PDF of phase of Rayleigh Distribution ’); xlabel(’\theta - ->’); ylabel(’’p(\theta) - ->’); grid;

Using randn function in MATLAB two free indistinguishably appropriated Gaussian random arrays are created and the envelope of their sum is entirely computed to give Rayleigh fading process. To plot the pdf of the created process a histogram is used and its phase plot is likewise drawn. Simulation Results:

Figure 3.5

Simulation results.

86

3.3

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

BPSK Modulation and Demodulation

Double Phase Shift Keying (BPSK) [5] is a kind of automated direction strategy in which we send one piece for each image, i.e., ’0’ or a ’1.’ In this way, the bit rate and image rate are the same. Regarding a reference bearer, we can have a stage move of 0o or 180o , which relies on the message bit. For example, we can have the following with transmitted band-pass pictures:  2E cos(2πf t) → represents  1 (3.7) S1 = T  2E S2 = (3.8) cos(2πf t + π) → represents  0 T or  2E cos(2πf t) → represents  0 S2 = (3.9) T Where ’E’ is the image vitality, ’T’ is the image era and f is the recurrence of the transporter. We get a solitary orthonormal premise work utilizing Gram-Schmidt orthogonalization, and it is given as:  2 ϕ1 = cos(2πf t) (3.10) T

3.3.1

BPSK Modulation

By and by, we can without a lot of a stretch see that the two waveforms of S0 and S1 are changed concerning each other and we can use the following intend to plot a BPSK modulator:

Figure 3.6

BPSK modulator.

BPSK MODULATION AND DEMODULATION

3.3.2

87

BPSK Demodulation

We do sound demodulation of the BPSK movement at the recipient. Insightful demodulation requires the persuaded signal to be expanded with the transporter having indistinct repeat and stage from the transmitter. The stage synchronization is commonly an expert using Phase Locked Loop (PLL) at the beneficiary. PLL execution isn’t done here; rather we expect it comes full circle and organizes synchronization.

Figure 3.7

BPSK demodulator.

The square framework of BPSK modulator is shown in Figure 3.7. After the increase with the carrier (orthonormal commence work), the signal is constellated over the picture length ’T’ and tried. By then thresholding is associated with choose whether a ’1’ was sent (+ve voltage), or a ’0’ was sent (- ve voltage). The MATLAB generation code is given below. Here, for ease, the bit rate is settled to 1 bit/s (i.e., T = 1 second). It is also acknowledged that Phased Locked Loop (PLL) has quite recently achieved redress organize synchronization. CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

clear all; close all; %------------------------------------------------------------------% Nb is the number of bits to be transmitted % Bit rate is assumed to be 1 bit/s; %------------------------------------------------------------------T =1; %------------------------------------------------------------------% bits to be transmitted B = [1 0 1 0 1] %------------------------------------------------------------------% Rb is the bit rate in bits/second %------------------------------------------------------------------NRZ_out = []; RZ_out = []; Manchester_out = []; %------------------------------------------------------------------%Vp is the peak voltage +v of the NRZ waveform %------------------------------------------------------------------Vp = 1; %------------------------------------------------------------------%Here we encode input bistream as Bipolar NRZ - L waveform %------------------------------------------------------------------For index = 1:size(b,2) If b(index) == 1 NRZ_out = [NRZ_out ones(1,200)*Vp];

88 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Elseif b(index) == 0 NRZ_out = [NRZ_out ones(1,200)*(-Vp)]; End End %------------------------------------------------------------------% Generated bit stream impulses %------------------------------------------------------------------Figure(1); Stem(b); Xlabel(’Time (seconds) -- >’) Ylabel(’ Amplitude (Volts) ->’) Title(’Impulses of bits to be transmitted’); Figure(2); Plot(NRZ_out); Xlabel(’ Time (Seconds) ->’); Ylabel(’Amplitude (volts) ->’); Title(’Generated NRZ signal’); T =0.005:0.005:5; %------------------------------------------------------------------%Frequency of the carrier F = 5; %------------------------------------------------------------------%Here we generate the moduleted singal by multiplying it with %carrier (basis function) %------------------------------------------------------------------Moduled =NRZ_out.*(sqrt(2/T)*cos(2*pi*f*t)); Figure; Plot(Modulated); Xlabel(’Time (seconds) ->’); Ylabel(’Amplitude (Volts) -- >’); Title(’BPSKModulated Signal’); Y = []; %------------------------------------------------------------------%We begin demodulation by multiplying the received signal again with %the carrier (basis function) %------------------------------------------------------------------Demodulated = Modulated.*(sqrt(2/T)*cos(2*pi*f*t)); %------------------------------------------------------------------%Here we perform the integration over time period T using trapz %Integrator is an important part of correlator receiver used here %------------------------------------------------------------------For i=1:200:size(demodulated,2) Y= [y trapz(t(i:i+199), demodulated(i:i+199))]; End Received = y>0; Figure; Stem(received) Title(’Impilses of received bits’); Xlabel(’Time (Seconds) ->’); Ylabel(’Amplitude (Volts)’)

Simulation Results: The output of the MATLAB code provides more insight into the modulation techniques. Apart from plotting the modulated and demodulated signal, it also shows the constellation at transmitter/receiver and the Power Spectral Density of the BPSK modulated signal.

89

QPSK MODULATION AND DEMODULATION

Figure 3.8

3.4

Sampling and results.

QPSK Modulation and Demodulation

Quadrature Phase Shift Keying (QPSK)[5] is a sort of stage direction technique, in which two information bits (joined as one picture) are adjusted as soon as possible, picking one among the 4 carriers arrange move states. QPSK movement inside picture term Tsym values are given s(t) = Acos[2πf ct + θn ], 0 = t = Tsym , n = 1, 2, 3, 4

(3.11)

where the signal phase is given by θn = (2n1)

π 4

(3.12) 7π 4

radians.

s(t) = Acosθn cos(2πfc t) − Asinθn sin(2πfc t) = sni φi (t) + snq φq (t)

(3.13)

Therefore, the four possible initial signal phases are Equation (3.11) can be rewritten as

π 3π 5π 4, 4 , 4

and

The enunciation shows usage of two orthonormal preface limits: (φi (t), (φq (t))(φi (t), (φq (t))

(3.14)

The above expression indicates the use of two orthonormal basis functions: < φi (t), φq (t) >

90

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

together with the inphase and quadrature signaling points: < sni , snq > Therefore, on a two-dimensional coordinate system with the axes set to φi (t) and φq (t), the QPSK signal is represented by four constellation points dictated by the vectors < sni , snq > with n = 1, 2, 3, 4. 3.4.1

QPSK Transmitter

The QPSK transmitter, shown in Figure 3.9, is executed as a MATLAB work qpsk mod. In this execution, a splitter segregates the odd and even bits from the created information bits. Each flood of different bits, as well as even bits, are changed over NRZ mastermind parallel.

Figure 3.9

Waveform simulation model for QPSK modulation.

CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14

clc; clear all; bits = 1000000; data=randint(1,bits)>0.5; %---------------------debugging------------------------------------%data-[1 1 1] %------------------------------------------------------------------Ebno=0:10; BER=zeros(1,length(data)/2; I=zeros(1,col); Q=I; I=data(1:2:bits-1); Q=data(2:2:bits); I= -2.*I+1;

QPSK MODULATION AND DEMODULATION

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

91

Q= -2.*Q+1; Symb=I+i.*Q; %--------Filter----------------------------------------------------Psf=ones(1,1); %------------------------------------------------------------------M=length(psf); For i=1:length(ebno) %------------------------------------------------------------------% inserting zeros between the bits w.r,t number of coefficients of % PSF to pass the bit stream from the PSF %------------------------------------------------------------------Z=zeros(M-1,bits/2); Upsamp=[symb;z]; Upsamp2=reshape(upsamp,1,(M)*bits/2); %------------------------------------------------------------------%passing the symbols from PSF %tx_symb=conv(real(upsamp2),psf)+j*Conv(imag(upsamp2,psf); %------------------------------------------------------------------Tx_symb=conv(upsamp2,psf); %----------------CHANNEL-------------------------------------------%Random noise generation and addition to the signal %------------------------------------------------------------------Npsd=10.ˆ(ebno(i)/10); n_var=1/sqrt(2.*npsd); rx_symb=tx_symb+(n_var*randn(1,length(tx_symb)) +j*n_var*randn(1,length(tx_symb))); %--------------------RECEIVER--------------------------------------rx_match=conv(rx_symb,psf); rx=rx_match(M:M:length(rx_match)); rx=rx(1:1:bits/2); recv_bits=zeros(1,bits); %------------------------------------------------------------------%demapping %------------------------------------------------------------------K=1; For ii=1:bits/2 recv_bits(k)= -(sign(real(rx(ii)))-1)/2; recv_bits(k+1)=-(sign(imag(rx(ii))) -1/2; k=k+2; end %sign(real(rx)) %sign(imag(rx)) %data %tx_symb %rx_symb %recv_bits %------------------------------------------------------------------%---SIMULATED BIT ERROR RATE---errors=find(xor(recv_bits,data)); errors=size(errors,2); BER(i)=errors/bits;

92 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

%------------------------------------------------------------------End Fs=1; N_pt=2ˆ9; Tx_spec=fft(tx_symb,n_pt); F= -fs/n_pt:fs/2-fs/n_pt; Figure Plot(f,abs(fftshift(tx_spec))); Title(signal Spectrum for signal with Rectangular Pulse Shaping for QPSK;); Xlabel(’Fequency [Hz]’); Ylabel(’x(F)’); Figure Semilogy(ebno,BER,’b.-’); Hold on; Thr=0.5*erfc(sqrt(10.ˆ(ebno/10))); Semilogy(ebno,thr,’rx-’); Xlabel(’Eb/No (dB)’ ); Ylabel(’Bit Error rate’); Title(’Simulated Vs Theoritical Bit Error Rate for QSPK’); Legend(’Simulation’,’Theory’); grid on;

Figure 3.10

Timing diagram for BPSK and QPSK modulations.

Figure 3.10 shows the diagrammatic representation for BPSK and QPSK. For BPSK, change picture range of each and every piece is similar to bit term. Anyway, for QPSK picture length is twice the bit length: Tsym = 2Tb Tsym = 2Tb

(3.15)

QPSK MODULATION AND DEMODULATION

93

Thusly, if the QPSK pictures were transmitted at a similar rate as BPSK, evidently QPSK transmits twice the data which BPSK transmits. In the wake of oversampling and heartbeat framing, it is normally apparent that the signal on the I-arm and Q-arm are BPSK signals with picture term 2Tb . The signal on the in-arrange arm is then copied by cos(2πfc t) and the signal on the quadrature arm is expanded by −sin(2πfc t). QPSK adjusted is obtained by including the signal from both in-stage and quadrature arms.

3.4.2

QPSK Receiver

In light of its remarkable relationship with BPSK, the QPSK beneficiary acknowledges the slightest troublesome casing, as shown in Figure 3.11. In execution, I and Q channel signals were demodulated similarly in the BPSK demodulation. At the end of demodulation, I and Q channel progressions are stabilized together. The limit qpsk_demodimplements a QPSK demodulator, as indicated in Figure 3.11.

Figure 3.11

3.4.3

Waveform simulation model for QPSK demodulation.

Performance Simulation over AWGN

The whole waveform generation for the already specified QPSK change and demodulation is given straight away. The signal incorporates, making discretionary message bits, altering them using QPSK adjust, the development of awgn channel multiplexed with the proposition movement and result in demodulating the disorderly signals using QPSK infuence. The waveforms at the distinctive periods of the modulator are shown in Figure 3.12.

94

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Figure 3.12

Simulated QPSK waveforms at the transmitter side.

The execution reenactment for the QPSK transmitter-authority blend was further coded in the code given above, and the resulting piece screw up rate execution curve will be the same as that of customary BPSK. 3.5 3.5.1

Image Error Rate vs Signal-to-Noise Ratio M-QAM Modulation

In M-ASK change method the information pictures (each k = log2 (M ) bit wide) are encoded into the abundance of the sinusoidal conveyor. In M-PSK changing the data is encoded by the time of the sinusoidal carrier. M-QAM turns for dull control strategy where the information is encoded in both plentifulness as well as the time of sinusoidal transporter. It stabilizes M-ASK and M-PSK direction systems. M-QAM change method is a 2-D adjust framework which requires two orthonormal introduce limits [10]. The M-QAM regulated signals are  2 cos (2πfc t) 0 ≤ t ≤ Ts (3.16) φI (t) = Ts  2 cos (2πfc t) 0 ≤ t ≤ Ts (3.17) φQ (t) = Ts

IMAGE ERROR RATE VS SIGNAL-TO-NOISE RATIO

95

The M-QAM modulated signal is represented as 



2 cos (2πfc t) , 0 ≤ t ≤ Ts , i = 1..M Ts (3.18) Here, VI,I and VQ,I are the amplitudes of the quadrature bearers abundance balanced by the data images. Si (t) = VI,i

3.5.2

2 cos (2πfc t) + VQ,i Ts

Baseband Rectangular M-QAM Modulator

There exist other constellations that are more efficient (in terms of energy required to achieve same error probability) than the standard rectangular constellation. But due to its simplicity in modulation and demodulation, square constellations are preferred. In practice, the information symbols are gray coded in order to restrict the erroneous symbol decisions to single bit error; the adjacent symbols in the transmitter constellation should not differ more than one bit. Usually, the gray coded symbols are separated into in-phase and quadrature bits and then mapped to M-QAM constellation [10]. The rectangular configuration of QAM makes it easier to constellate the previously mentioned steps into a simplified Look-Up-Table (LUT) approach (Figure 3.13).

Figure 3.13

M-QAM modulator.

The values in the LUT (where the reference constellation is stored) are normalized by the normalization mentioned above factor, and then the 64-QAM signal is generated. The simulation model for M-QAM modulation is given in Figure 3.14. The receiver uses Euclidean distance as a metric to decide on the received symbols.

96

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Figure 3.14

M-QAM simulation model.

Matlab Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

%------------------------------------------------------------------% Demonstration of Eb/N0 Vs SER for M-QAM modulation scheme %------------------------------------------------------------------clear;clc; %---------Input Fields-----------------------%Number of input symbols N=10000; %Define EbN0dB range for simulation EbN0dB = -6:2:12; %for 16-QAM modulation. M=16; %------------------------------------------------------------------refArray =1/sqrt(10)*[-3-3j,-3-1j,-3+3j,-3+1j,-1-3j,-1-1j,-1+3j, -1+1j,3-3j,3-1j,3+3j,3+1j,1-3j,1-1j,1+3j,1+1j]; symErrSimulated = zeros(1,length(EbN0dB)); k=log2(M); EsN0dB = EbN0dB + 10*log10(k); %------------------------------------------------------------------%-Generating a uniformly distributed random numbers in the % set [0,1,2,..,M-1] %------------------------------------------------------------------data=ceil(M.*rand(N,1))-1; %16-QAM Constellation mapping with Gray coding s=refArray(data+1); %Reference Constellation for demodulation and Error rate computation refI = real(refArray); refQ = imag(refArray); %------------------------------------------------------------------%Place holder for Symbol Error values for each Es/N0 %for particular M value %------------------------------------------------------------------index=1; figure(1); subplot(1,2,1); plot(real(s),imag(s),’r*’); title(’Constellation diagram for Transmitted Symbols’);

IMAGE ERROR RATE VS SIGNAL-TO-NOISE RATIO

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

97

xlabel(’Inphase component’); ylabel(’Quadrature component’); subplot(1,2,2); for x=EsN0dB, %-------Channel Noise for various Es/N0----------------------------%Adding noise with variance according to the required Es/N0 %Standard deviation for AWGN Noise %------------------------------------------------------------------noiseVariance = 1/(10.ˆ(x/10)); noiseSigma = sqrt(noiseVariance/2); %Creating a complex noise for adding with M-QAM modulated signal %Noise is complex since M-QAM is in complex representation noise = noiseSigma*(randn(size(s))+1i*randn(size(s))); received = s + noise; %------------------------------------------------------------------% I-Q Branching %------------------------------------------------------------------r_i = real(received); r_q = imag(received); %------------------------------------------------------------------%Decision Maker-Compute(r_i-s_i)ˆ2+(r_q-s_q)ˆ2 and % choose the smallest %------------------------------------------------------------------r_i_repmat = repmat(r_i,M,1); r_q_repmat = repmat(r_q,M,1); plot(r_i,r_q,’*’); title([’Constellation diagram for Received Symbols Eb/N0=’ num2str(x-10*log10(k)) ’dB’]); xlabel(’Inphase component’); ylabel(’Quadrature component’); pause; %place holder for distance metric distance = zeros(M,N); minDistIndex=zeros(N,1); for j=1:N %---Distance computation - (r_i-s_i)ˆ2+(r_q-s_q)ˆ2 -------------distance(:,j)=(r_i_repmat(:,j)-refI’).ˆ2 +(r_q_repmat(:,j)-refQ’).ˆ2; %Capture the index in the array where the minimum distance occurs [dummy,minDistIndex(j)]=min(distance(:,j)); end %The index becomes the decoded symbol y = minDistIndex - 1; %--------------Symbol Error Rate Calculation----------------------dataCap = y; symErrSimulated(1,index) = sum(dataCap˜=data)/N; index=index+1; end %----- Compute Theoretical Symbol Error Rates --------------------%EsN0lin = 10.ˆ(EsN0dB/10); EbN0lin = 10.ˆ(EbN0dB/10); symErrTheory = 2*(1-1/sqrt(M))*erfc(sqrt(3/2*k*EbN0lin/(M-1))); %------------------------------------------------------------------% Plotting commands %-------------------------------------------------------------------

98 95 96 97 98 99 100 101 102

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

figure(2); semilogy(EbN0dB,symErrTheory,’r-’); hold on; semilogy(EbN0dB,symErrSimulated,’b*’); legend(’16QAM-Theory’,’16QAM-Sim’); xlabel(’Eb/N0(dB)’); ylabel(’Symbol Error Rate (Ps)’); grid on;

Simulation results:

Figure 3.15

Samples of in-phase component.

RECREATION OF OFDM FRAMEWORK

3.6

99

Recreation of OFDM Framework

In modulations, information is mapped onto changes in frequency, phase or amplitude (or a combination of them) of a carrier signal. Multiplexing deals with allocation/accommodation of users in a given bandwidth (i.e., it deals with allocation of available resource). OFDM (Orthogonal frequency division multiplexing) is a combination of modulation and multiplexing. In this technique, the given resource (bandwidth) is shared among individual modulated data sources. Normal modulation techniques (like AM, PM, FM, BPSK, QPSK, etc.) are single carrier modulation techniques, in which the incoming information is modulated over a single carrier. OFDM is a multicarrier modulation technique, which employs several carriers, within the allocated bandwidth, to convey the information from source to destination. Each carrier may employ one of the several available digital modulation techniques (BPSK, QPSK, QAM, etc.) [8]. OFDM is very effective for communication over channels with frequency selective fading (different frequency components of the signal experience different fading). It is very difficult to handle frequency selective fading in the receiver, in which case, the design of the receiver is hugely complex. Instead of trying to mitigate frequency selective fading as a whole (which occurs when a huge bandwidth is allocated for the data transmission over a frequency selective fading channel), OFDM mitigates the problem by converting the entire frequency selective fading channel into small flat fading channels (as seen by the individual subcarriers). Flat fading is easier to combat (when compared to frequency selective fading) by employing simple error correction and equalization schemes [12]. To reenact an OFDM structure, the following arrangement parameters are crucial (Figure 3.16).

Figure 3.16

An OFDM communication architecture with a cyclic prefix.

100

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

Consider that we want to send the following data bits using OFDM: D = {d0 , d1 , d2 , ...}

(3.19)

The first thing that should be considered in designing the OFDM transmitter is the number of subcarriers required to send the given data. As a generic case, let’s assume that we have N subcarriers. Each subcarrier is centered at frequencies that are orthogonal to each other (usually multiples of frequencies). The second design parameter could be the modulation format that we wish to use. An OFDM signal can be constructed using any of the following digital modulation techniques, namely BPSK, QPSK, QAM, etc. The data (D) has to be first converted from serial stream to parallel stream depending on the number of subcarriers (N). Since we assumed that there are N subcarriers allowed for the OFDM transmission, we name the subcarriers from 0 to N − 1. Now, the Serial to Parallel converter takes the serial stream of input bits and outputs N parallel streams (indexed from 0 to N − 1). These parallel streams are individually converted into the required digital modulation format (BPSK, QPSK, QAM, etc.). Let us call this output S0 , S1 , .., SN . The conversion of parallel data (D) into the digitally modulated data (S) is usually achieved by a constellation mapper, which is essentially a lookup table (LUT). Once the data bits are converted to required modulation format, they need to be superimposed on the required orthogonal subcarriers for transmission. This is achieved by a series of N parallel sinusoidal oscillators tuned to N orthogonal frequencies (f0 , f1 , .., fN −1 ). Finally, the resultant output from the parallel arms are summed up together to produce the OFDM signal. The following figure illustrates the basic concept of OFDM transmission (Note: In order to give a simple explanation to illustrate the underlying concept, the usual IFFT/FFT blocks that are used in actual OFDM system, are not used in the block diagram). Given parameters in the spec: 1 2 3 4 5 6 7 8

%FFT size or total number of subcarriers (used + unused) 64 N=64; %Number of data subcarriers 48 Nsd = 48; %Number of pilot subcarriers 4 Nsp = 4; % OFDM bandwidth ofdmBW = 20 * 10ˆ6 ;

Derived parameters: 1 2 3 4 5 6 7 8 9 10

%Bandwidth for each subcarrier-include all used and unused subcarries deltaF = ofdmBW/N; % IFFT or FFT period = 3.2us Tfft = 1/deltaF; % Guard interval duration - duration of cyclic prefix % 1/4th portion of OFDM symbols Tgi = Tfft/4;

RECREATION OF OFDM FRAMEWORK

11 12 13 14 15 16 17 18 19 20 21

101

% Total duration of BPSK-OFDM symbol = Guard time + FFT period Tsignal = Tgi+Tfft; %Number of symbols allocated to cyclic prefix Ncp = N*Tgi/Tfft; % Number of total used subcarriers Nst = Nsd + Nsp; %BPSK the number of Bits per Symbol is same as number of subcarriers nBitsPerSym=Nst;

The direct for this circumstance is shown as a clear AWGN channel. It is an AWGN channel; prerequisite procedure is not present for the repeat region equalizer. Currently, we are working in the AWGN channels; here we removed the repeat space equalizer from the above layout. 3.6.1

Figuring (Es /N0 ) or (Eb /N0 ) for OFDM Framework

Created 0 mean and unit variance disturbance must be scaled in a like manner to address (Eb /N0 ) or (Es /N0 ). So, both the Eb /N0 and Es /N0 were similar for BPSK. Regardless of OFDM BPSK structure, they differ. This is because every OFDM picture has extra overhead in time territory as well as repeat space. 3.6.2

Impact of Cyclic Prefix on Es /N

Going with chart portrays the possibility of the cyclic prefix. Every OFDM picture has useful data as well as overhead. Here, bit imperativeness addresses essentialness enclosed with valuable bits. For example, bit essentialness which helps to spread over N bits. Over the helpful information, extra Ncp bits were incorporated as the cyclic prefix, which are those that are outlining the overhead.

Figure 3.17

Effect of cyclic prefix on Es /N0 .

102

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

The relationship is shown as Es (N + Ncp ) = N Eb

(3.20)

which translates to the equation below. Es = 3.6.3

N × Eb N + Ncp

(3.21)

Effect of Unused Subcarriers on Es/N

Since specified before, only some of the subcarriers are utilized for transmission. From the aggregate N subcarriers, just Nst transporters are being used for OFDM images transmission (they incorporate the two information and pilot subcarriers). Once more, in the recurrence area, the valuable piece vitality is spread crosswise over Nst subcarriers, though the image vitality is spread crosswise over N subcarriers. Es × N = Nst × Eb

(3.22)

which translate to the equation below Es =

Nst × Eb N

(3.23)

In Equations (3.21) and (3.22), the overall effect of both cyclic prefix and unused subcarriers on Es /N0 is given by    ES Nst Eb N = (3.24) N0 Ncp + N N N0 which, when converted to dB yields the following relationship:       ES Nst Eb N dB + dB + dB = N0 Ncp + N N N0 db

(3.25)

Since Ncp cyclic prefix is added to the OFDM symbol, the output signal from the parallel to serial converter has to be boosted to compensate for the wastage of energy associated with the addition of a cyclic prefix. To correctly generate the required SNR in MATLAB, the signal term at the output of the parallel to serial converter has to be scaled as follows:  Ncp + N Boosted OF DM signal = × OF DM signal (3.26) N The received signal is represented as (for the given Eb /N0 ). y = boosted OF DM signal + required noise

(3.27)

RECREATION OF OFDM FRAMEWORK

3.6.4

103

Arrangement of Subcarriers

The IEEE 802.11 specification specifies how to arrange the given subcarriers. The 52 used subcarriers (data + pilot) are assigned numbers from −26, −25, .. − 2, −1 and 1, 2, .., 25, 26. The following figure illustrates the scheme of assigning these subcarriers to the IFFT inputs.

Figure 3.18

3.6.5

Assignment of OFDM subcarriers.

MATLAB Sample Code

OFDM Transmitter part code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

clc; clear all; close all; %------------------------------------------------------------------% Initiation %------------------------------------------------------------------%Number of bits per channel extended to 128 no_of_data_bits = 64 %Number of subcarrier channel M =4 %Total number of bits to be transmitted at the transmitter n=256; %Size of each OFDM block to add cyclic prefix block_size = 16; %Length of the cyclic prefix cp_len = floor(0.1 * block_size); %------------------------------------------------------------------% Transmitter %------------------------------------------------------------------% Source generation and modulation %-------------------------------------------------------------------

104 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

% Generate random data source to be transmitted of length 64 data = randsrc(1, no_of_data_bits, 0:M-1); figure(1),stem(data); grid on; xlabel(’Data Points’); ylabel(’Amplitude’) title(’Original Data ’) %------------------------------------------------------------------% Perform QPSK modulation on the input source data %------------------------------------------------------------------qpsk_modulated_data = pskmod(data, M); figure(2),stem(qpsk_modulated_data); title(’QPSK Modulation ’) %------------------------------------------------------------------% Converting the series data stream into four parallel data stream % to form four sub carriers %------------------------------------------------------------------S2P = reshape(qpsk_modulated_data, no_of_data_bits/M,M) Sub_carrier1 = S2P(:,1) Sub_carrier2 = S2P(:,2) Sub_carrier3 = S2P(:,3) Sub_carrier4 = S2P(:,4) figure(3), subplot(4,1,1), stem(Sub_carrier1), title(’Subcarrier1’), grid on; subplot(4,1,2), stem(Sub_carrier2), title(’Subcarrier2’),grid on; subplot(4,1,3), stem(Sub_carrier3), title(’Subcarrier3’), grid on; subplot(4,1,4), stem(Sub_carrier4), title(’Subcarrier4’), grid on; %------------------------------------------------------------------% IFFT OF FOUR SUB_CARRIERS %------------------------------------------------------------------number_of_subcarriers=4; cp_start=block_size-cp_len; ifft_Subcarrier1 = ifft(Sub_carrier1) ifft_Subcarrier2 = ifft(Sub_carrier2) ifft_Subcarrier3 = ifft(Sub_carrier3) ifft_Subcarrier4 = ifft(Sub_carrier4) figure(4), subplot(4,1,1), plot(real(ifft_Subcarrier1),’r’), title(’IFFT on all the sub-carriers’) subplot(4,1,2), plot(real(ifft_Subcarrier2),’c’)

RECREATION OF OFDM FRAMEWORK

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

105

subplot(4,1,3), plot(real(ifft_Subcarrier3),’b’) subplot(4,1,4), plot(real(ifft_Subcarrier4),’g’) %------------------------------------------------------------------% ADD-CYCLIC PREFIX %------------------------------------------------------------------for i=1:number_of_subcarriers, % 16 is the ifft point ifft_Subcarrier(:,i) = ifft((S2P(:,i)),16) for j=1:cp_len, cyclic_prefix(j,i) = ifft_Subcarrier(j+cp_start,i) end Append_prefix(:,i)=vertcat(cyclic_prefix(:,i),ifft_Subcarrier(:,i)) %------------------------------------------------------------------% Appends prefix to each subcarriers %------------------------------------------------------------------end A1=Append_prefix(:,1); A2=Append_prefix(:,2); A3=Append_prefix(:,3); A4=Append_prefix(:,4); figure(5), subplot(4,1,1), plot(real(A1),’r’), title(’Cyclic prefix added to all the sub-carriers’) subplot(4,1,2), plot(real(A2),’c’) subplot(4,1,3), plot(real(A3),’b’) subplot(4,1,4), plot(real(A4),’g’) figure(11), plot((real(A1)),’r’), title(’Orthogonality’), hold on, plot((real(A2)),’c’), hold on, plot((real(A3)),’b’), hold on, plot((real(A4)),’g’), hold on, grid on; %------------------------------------------------------------------%Convert to serial stream for transmission %------------------------------------------------------------------[rows_Append_prefix cols_Append_prefix]=size(Append_prefix) len_ofdm_data = rows_Append_prefix*cols_Append_prefix %------------------------------------------------------------------% OFDM signal to be transmitted

106 138 139 140 141 142 143 144 145 146

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

%------------------------------------------------------------------ofdm_signal = reshape(Append_prefix, 1, len_ofdm_data); figure(6), plot(real(ofdm_signal)); xlabel(’Time’); ylabel(’Amplitude’); title(’OFDM Signal’); grid on; %-------------------------------------------------------------------

Passing time domain data through channel and AWGN 1 2 3 4 5 6 7 8 9 10 11 12 13 14

%------------------------------------------------------------------channel = randn(1,2) + sqrt(-1)*randn(1,2); after_channel = filter(channel, 1, ofdm_signal); awgn_noise = awgn(zeros(1,length(after_channel)),0); %------------------------------------------------------------------% With AWGN noise %------------------------------------------------------------------recvd_signal = awgn_noise+after_channel; figure(7), plot(real(recvd_signal)),xlabel(’Time’); ylabel(’Amplitude’); title(’OFDM Signal after passing through channel’); grid on; %-------------------------------------------------------------------

OFDM receiver part 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

%------------------------------------------------------------------recvd_signal_paralleled=reshape(recvd_signal,rows_Append_prefix, cols_Append_prefix); %------------------------------------------------------------------% Remove cyclic Prefix %------------------------------------------------------------------recvd_signal_paralleled(1:cp_len,:)=[]; R1=recvd_signal_paralleled(:,1); R2=recvd_signal_paralleled(:,2); R3=recvd_signal_paralleled(:,3); R4=recvd_signal_paralleled(:,4); figure(8),plot((imag(R1)),’r’), subplot(4,1,1),plot(real(R1),’r’), title(’Cyclic prefix removed from the four sub-carriers’) subplot(4,1,2),plot(real(R2),’c’) subplot(4,1,3),plot(real(R3),’b’) subplot(4,1,4),plot(real(R4),’g’) %------------------------------------------------------------------% FFT Of recievied signal %------------------------------------------------------------------for i=1:number_of_subcarriers, % FFT fft_data(:,i) = fft(recvd_signal_paralleled(:,i),16); end F1=fft_data(:,1);

RECREATION OF OFDM FRAMEWORK

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

107

F2=fft_data(:,2); F3=fft_data(:,3); F4=fft_data(:,4); figure(9), subplot(4,1,1), plot(real(F1),’r’), title(’FFT of all the four sub-carriers’) subplot(4,1,2), plot(real(F2),’c’) subplot(4,1,3), plot(real(F3),’b’) subplot(4,1,4), plot(real(F4),’g’) %------------------------------------------------------------------% Signal Reconstructed %------------------------------------------------------------------% Conversion to serial and demodulationa %------------------------------------------------------------------recvd_serial_data = reshape(fft_data, 1,(16*4)); qpsk_demodulated_data = pskdemod(recvd_serial_data,4); figure(10) stem(data) hold on stem(qpsk_demodulated_data,’rx’); grid on; xlabel(’Data Points’); ylabel(’Amplitude’); title(’Recieved Signal with error’)

Simulated Result: From the simulated result, it can be ascertained that the OFDMBPSK modulation has no advantage over a normal BPSK system in AWGN. OFDM proves to be effective in multipath environments.

Figure 3.19

Eb /N0 Vs BER for BPSK-OFDM over AWGN.

108

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

OFDM Basic Tx-Rx Chain

Figure 3.20

OFDM essential Tx-Rx chain.

The OFDM MATLAB code for the block schematic in Figure 3.20 is provided below for download. OFDM transmitter in this example consists of FEC encoder, BPSK modulator, and 256-point IFFT. OFDM receiver part consists of FFT, BPSK demodulator and Viterbi decoder. BER curve for this OFDM MATLAB model is mentioned below taken after passing the transmitter data from AWGN channel.

Figure 3.21

3.7

BER results.

Conclusion

This chapter introduced digital communication using network modeling and how to create a model with the software which is not vulnerable and can be accessible all over the globe for the communications. Described in this chapter were data transmission mechanisms, how to create a secure channel, and how to modify data for

CONCLUSION

109

the sake of security. Methods of communicating with the secure channel is one of the things students will find of interest in this chapter. This chapter also dealt with different simulation models explained with basic sample codes, all of which are executable and error free. Students can practice the codes in the terminal and learn new things from the book. QPSK demodulation theory has been explained well in the chapter, which also contains other interesting topics like recreation frameworks and the importance of recreation and the other frameworks which are used for better communication and also for better secured channel creation and implementation.

REFERENCES 1. IEEE 802.11 specification - Orthogonal frequency division multiplexing (OFDM) PHY specification for the 5 GHz band- chapter 17, Wireless Communication Systems in MATLAB, ISBN: 978-1720114352 2. Lloyd N. Trefethen, David Bau III, Numerical linear algebra, Philadelphia: Society for Industrial and Applied Mathematics, ISBN 978-0-89871-361-9, pp.56 3. Feng, J. (2007). Digital Communications and Signal Processing with MATLAB Examples. Lecture Notes. The University of Warwick. 4. Etemadi, F., Heydari, P.,& Jafarkhani, H. (2018). On Analog QAM Demodulation for Millimeter-Wave Communications. IEEE Transactions on Circuits and Systems II: Express Briefs. 5. Munjal, S., Lathwal, H., Kumar, R., & Verma, V. (2018). COMPARATIVE ANALYSIS OF BPSK, QPSK, QAM MODULATION, AND DEMODULATION TECHNIQUE WITH BIT ERROR RATE USING MATLAB 2014A. Journal of Advances in Computational Intelligence and Communication Technologies, 2(1), 46-48. 6. Upase, S. J., & Labade, R. P. (2018, February). Design and Implementation of Encrypted SDR and Study of Noise in High-Level System Architecture Using MATLAB. In 2018 International Conference on Advances in Communication and Computing Technology (ICACCT) (pp. 197-202). IEEE. 7. Razali, S. (1999). Digital communication system simulation using matlab (Doctoral dissertation, Universiti Teknologi Malaysia). 8. Viswanathan, M. (2013). Simulation of digital communication systems using Matlab. Mathuranathan Viswanathan at Smashwords. 9. Silage, D. (2009). Digital Communication Systems Using MATLAB and Simulink. Bookstand Pub. 10. Patel, J. N., & Dalal, U. D. (2007, December). A comparative performance analysis of OFDM using MATLAB simulation with M-PSK and M-QAM mapping. In Conference on Computational Intelligence and Multimedia Applications, 2007. International Conference on (Vol. 4, pp. 406-410). IEEE. 11. Ghassemlooy, Z., Popoola, W., & Rajbhandari, S. (2012). Optical wireless communications: system and channel modeling with Matlab. CRC press. 12. Cho, Y. S., Kim, J., Yang, W. Y., & Kang, C. G. (2010). MIMO-OFDM wireless communications with MATLAB. John Wiley & Sons.

110

DIGITAL COMMUNICATION SYSTEM SIMULATION USING MATLAB

13. Ingle, V. K., & Proakis, J. G. (2016). Digital Signal Processing Using MATLAB: A Problem Solving Companion. Cengage Learning. 14. Blanchet, G., & Charbit, M. (2006). Digital signal and image processing using MATLAB (Vol. 4). London: Iste. 15. Milic, L. (Ed.). (2009). Multirate Filtering for Digital Signal Processing: MATLAB Applications: MATLAB Applications. IGI Global.

CHAPTER 4

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Abstract In this chapter, we explain how to perform statistical analysis of network data utilizing MATLAB starting from affiliation systems/networks with examples. We also explain time series analysis, statistical stationarity, time series decomposition, de-trending, curve fitting, digital filtering, recurrence reaction, and connection between recurrence reaction to spline parameter. Next we have provide details about autocorrelation, test for independence, linear autoregressive models, etc. Keywords: Statistical analysis, association network

Network Modeling, Simulation and Analysis in MATLAB. c 2019 Scrivener Publishing By Dac-Nhuong Le et al. Copyright 

111

112

4.1

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Introduction to Association Networks

We can utilize ARN as an orderly apparatus to include choice [1-2]. The means included are: 1. Setting up the information for affiliation governs mining. This involves changing the data into exchanges where every exchange is an itemset. Information, where factors are, should be discredited. 2. Note that ARNs are target driven so those association rules which are of interest are those that in a particular or roundabout way are related to the objective hub. An affiliation control calculation can be altered to produce just the essential principles. In any case, since our goal is to show the standard (as opposed to the particular case), higher estimations of the edge may be more reasonable.

Figure 4.1

Flowchart of association rules implementation.

3. Fabricate the association rule network. This development has two or three exceptional cases which should be managed adequately. We may likewise pick the best k rules (by sureness) for the given target focus point. The high position here is that we don’t need to demonstrate the affirmation (or here and there even the help). In any case, now we need to choose the “best k.” Another favored edge is that, for the most part, we can comparatively utilize the “best k” way to deal with oversight to discover leads in higher proportions to the ARN [3, 4]. 4. Apply a gathering-together depending on the ARN to evacuate the immense highlights (as for the physical space). On a fundamental level, ARN is a sortedout hypergraph. We can utilize a hypergraph gathering include as addressed [5].

INTRODUCTION TO ASSOCIATION NETWORKS

113

Figure 4.2 (a) ARN for contact lens data with target node as hard; (b) ARN for contact lens data with target node as soft.

5. The segments of the packets are a social affair of things (features) which are connected. Pick one part of the gathering as the contender incorporate. The number of conventions picked is a parameter and will require specific alteration. 6. Fabricate and test a quantifiable model (e.g., backslide) to formally test the association between the ward and the contender factors. ARN Examples For the contact lens example, we utilize all things considered essential, instructive record from the UCI chronicle [1-2] to show how ARNs can be used for a fuse choice. The ARN for the lens information is shown in Figure 4.3.

Figure 4.3 with ARN.

Schematic diagram showing the activity method of communication in a software

114

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Poor people variable is whether a patient ought to be fitted with hard contact focal centers, delicate contact focal concentrations or ought not to be equipped with contact focal core interests. There are four attributes. We fabricated an ARN where the objective quality is the class. Support and confirmation were picked as zero. Plainly, both ARNs (for hard and delicate focal centers) can be utilized to awaken highlights. We have finished a broad examination of the Open Source Software space utilizing ARN. Motivations behind interest can be gotten from [3, 6]. The OSS information was gotten to comprehend why certain things open from sourceforge .net wind up standard. This is a cross-sectional examination. Maybe a future issue is to utilize ARNs for examination of longitudinal information. 4.2 4.2.1

Time Series, Stationary, Time Series Decomposition, De-trending Time Series Analysis

In different applications, for example, physiology and performance, sweeping time course of action information bases are to be broken down, requiring the estimation of quick, nonlinear and unmistakable measures. Such measures have been made and acknowledged in business and freeware virtual things or conceived especially and energetically. The Measures of Analysis of Time Series (MATS) MATLAB device stash is relied upon to deal with a discretionary colossal strategy of scalar time course of action and enlists an enormous game plan of measures on them, also pondering the specification of changing measure parameters. The gathering of choices with included working environments for depiction of the results bolster different settings of time game plan examination; for example, the zone of segments changes in long information records, reinvestigating (surrogate or bootstrap) tests for independence in addition to linearity with different test bits of learning, and segment intensity of different measures in like manner, for different mixes of their parameters. The essential highlights of MATS are demonstrated in like manner, and the executed measures are briefly portrayed. The settlement of MATS is spread out on some right cases near the screen gets [7, 18, 22, 23]. Many made programming things join standard frameworks for time game plan examination. Business quantifiable packs, such as SPSS [8] and SAS Institute Inc. [9], have working environments on time blueprint which are extremely fundamental level executions of the standard Box-Jenkins approach on non-stationary time game plan. The business computational conditions of MATLAB (The MathWorks, Inc.) and SPLUS (Insightful Corp.) give distinctive gadget hold or modules that strategize with time course of action (MATLAB: Financial, Econometrics, Signal Handling, Neural Network and Wavelets; S-PLUS: FinMetrics, Wavelet, Environmental Details). Not so much standard, but rather more developed mechanical congregations of time game plan examination can be found in different business remain single programming bunches made for more specific employments of time course of action, and in two or three freeware packages, by and large gathering a game plan of ventures

TIME SERIES, STATIONARY, TIME SERIES DECOMPOSITION, DE-TRENDING

115

instead of a fused programming, for instance, the TISEAN package which constellates an entire game plan of procedures for the dynamical structure approach [10]. In some open-source MATLAB apparatus stash other chosen methods for dismembering a data time plan, for instance, the time course of action examination toolbox TSA [11]. In various applications, particularly when the structure is to some degree astounding, as in seismology, air, performance and physiology, the change of models from data can be a noteworthy task. There the intrigue is somewhat in compact data from a period approach to some emptied highlights or measures that can be as immediate as illuminating bits of information or as convoluted as the dependability of _t of a nonlinear model including many free parameters. Besides, the present issue may join diverse time game plan, e.g., different stock records or constant territories from the split of a long physiological pennant such as an electrocardiogram (ECG) or electroencephalogram (EEG). The errand of dealing with these issues is to delineate, detach or amass the time game plan in light of the assessed measures. The Measures of Analysis of Time Series toolbox MATS is made in MATLAB to meet the as of now said needs. The reason behind MATS isn’t just to finish unquestionably appreciated and all-around endeavored measures, but to present in the same way different measures, which have been beginning to appear late in the synthesis and might be helpful in getting properties of the time approach. Moreover, MATS give several sorts of pre-arranging of discretionary long game plans of scalar time course of action. MATS mishandle the graphical UI (GUI) of MATLAB to build up an easy to use condition and depiction of working environments. In the figuring of two or three procedures, works in the Signal Processing, System Identification and Statistics MATLAB instrument stash are called upon. Measures identified with specific instrument stash, for example, GARCH models [12], neural structures and wavelets, are not understood in MATS. To stimulate estimations while sifting for neighboring focuses, MATS utilizes k-D tree information structure worked in outside _les (.dll for Windows and .mexglx for Linux), which are kept up by MATLAB modifications 6.5 or later. 4.2.2

Stationarity

Statistical Stationarity: A stationary time course of action is one whose verifiable properties, for instance, mean, change, autocorrelation, et cetera, are all in all relentless after some time. Most truthful checking methods rely upon the assumption that the time plan can be rendered around stationary (i.e., “stationarized”) utilizing logical changes. A stationarized game plan is respectably easy to predict: you fundamentally envision that its quantifiable properties will be the same later on as they have previously been! The figures for the stationarized plan would then have the capacity to be “untransformed,” by exchanging whatever logical changes were used in advance to secure the principal course of action desired. (The straightforward components are normally managed by your item.) Thus, finding the gathering of changes anticipated that would stationarize a period game plan as often as possible

116

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

gives fundamental bits of knowledge in the sweep for a reasonable deciding model. Stationarizing a period plan through differencing (where required) is a basic bit of the route toward fitting an ARIMA illustrate, as discussed in the ARIMA pages of these notes. Most business and budgetary time courses of action are far from stationary when conveyed in their remarkable units of estimation, and even subsequent to discharging or normal change they will usually still show designs, cycles, self-assertive walking, and other non-stationary direct. In case the course of action has a stable long-run design and tends to come back to the example line following an exacerbation, it may be possible to stationarize it by de-floating (e.g., by fitting an example line and subtracting it out before fitting a model, or else by including the time record as a free factor in a backslide or ARIMA illustrate), perhaps related to logging or crumbling. Such a plan is said to be slant stationary. In any case, now and again even deinclining isn’t satisfactory to make the course of action stationary, in which case it may be imperative to transform it into a movement of period-to-period or possibly season-to-season contrasts. If the mean, change, and autocorrelations of the primary game plan are not reliable in time, even in the wake of de-slanting, perhaps the estimations of the modifications in the course of action between periods or between seasons will be enduring. Such a course of action is said to be refinement stationary. (From time to time it might be hard to separate between a course of action that is floating stationary and one that is differentiating stationary and an assumed unit root test may be used to locate a more entire arrangement. We will return to this topic later in the chapter.)

Figure 4.4

Time series plot for adjusted AUTOSALE/CPI.

The fundamental difference of a period game plan is the course of action of changes beginning with one period then onto the following. If Yt implies the estimation of the time game plan Y at period t, by then the vital qualification of Y at period t is proportionate to Yt − Yt−1 . In State illustrations, the important refinement of Y is imparted as DIF F (Y ), and in Regress it is Y DIF F 1. If the primary refinement of Y is stationary and moreover absolutely sporadic (not autoconnected), by then Y is depicted by a subjective walk appear: each regard is an unpredictable

TIME SERIES, STATIONARY, TIME SERIES DECOMPOSITION, DE-TRENDING

117

progress a long way from the past regard. In case the foremost differentiation of Y is stationary yet not absolutely unpredictable – i.e., if its impetus at period t is auto corresponded with its motivating force at earlier periods – then a further developed deciding model, for instance, exponential smoothing or ARIMA may be legitimate. (Note: if DIF F (Y ) is stationary and self-assertive, this exhibits a sporadic walk indicate appropriate for the primary course of action Y, not that a discretionary walk show should be fitted to DIF F (Y ). Fitting a subjective walk model to Y is sensibly indistinguishable to fitting a mean (reliable simply) model to DIF F (Y ).)

Figure 4.5

4.2.3

Time series chart with obtained output form.

Time Series Decomposition

Time arrangement deterioration includes isolating a period arrangement into a few unmistakable segments. There are three segments that are normally intriguing: Tt , a deterministic, non-seasonal mainstream drift segment. This segment is in some cases confined to being a direct pattern; however, higher-degree polynomials are additionally utilized. St is a deterministic occasional segment with known periodicity. This part catches level moves that rehash deliberately inside a similar period (e.g., month or quarter) between progressive years. Usually thought to be a disturbance part, occasional alteration is a procedure for disposing of it. It , a stochastic unpredictable segment. This part isn’t really a repetitive sound. It can display autocorrelation and cycles of flighty span. Hence, it is usually contemplated in the business cycle, and is typically the most intriguing part. There are three utilitarian structures that are regularly utilized for speaking to a period arrangement yt as an element of its pattern, occasional, and sporadic parts.

118

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Additive disintegration, where this is the established deterioration. It is fitting when there is no exponential development in the arrangement, and the adequacy of the occasional part stays consistent after some time. For identification from the pattern part, the regular and unpredictable segments are expected to vary around zero. Multiplicative disintegration, where this disintegration is suitable when there is exponential development in the arrangement, and the sufficiency of the regular part develops with the level of the arrangement. For identification from the pattern segment, the regular and unpredictable parts are accepted to change around one. Log-added substance decay, where this is a contrasting option to the multiplicative decay. On the off chance that the first arrangement has a multiplicative disintegration, at that point substance deterioration has been added to the logged arrangement. The logs can be best utilized when the time arrangement contains numerous little perceptions. For identification from the pattern part, the regular and unpredictable segments are accepted to vacillate around zero. You can appraise the pattern and regular parts by utilizing channels (moving midpoints) or parametric relapse models. Given assessments Tt and St , the sporadic segment is evaluated as utilizing the added substance decay, and utilizing the multiplicative decay. The arrangement (or on the other hand Tytt utilizing the multiplicative decay) is known as a de-trended arrangement. Thus, the arrangement yt −St (or Sytt ) is known as a de-seasonalized arrangement. 4.2.4

De-trending

Model in a period approach is an immediate, interminable change in some property of the strategy over the entire between times under scrutiny. Model is once in a while incorrectly depicted all in all arrangement change in the mean, at any rate it can comparatively hint change in other quantifiable properties. For example, treering topology of overviewed ring width which has a point of reference in instability. In normal time strategy examination, a period course of action was separated into model, standard or irregular segments, and sporadic changes, and the differing parts were contemplated self-governing. Every once in a while current examination strategies treat the strategy without such routine disintegrating; in any case, isolate thought of model is still reliably required. De-slanting is the quantifiable or numerical activity of expelling plan from the game plan. De-inclining is consistently connected with expel a part thought to turn or cloud the relationship of intrigue. In climatology, for instance, a temperature incline from the perspective of urban warming may darken a relationship between shadiness and air temperature. De-floating is once in a while utilized as a preprocessing advancement to configuration time approach for examination by frameworks that expect stationarity. Different elective strategies are accessible for de-inclining. Clear quick precedent in mean can be expelled by subtracting a base squares-fit straight line. More puzzled models may require varying methods.

TIME SERIES, STATIONARY, TIME SERIES DECOMPOSITION, DE-TRENDING

119

For instance, the cubic smoothing spline is generally utilized in dendrochronology to fit and evacuate ring-width slant, which most likely won’t be prompt or not even monotonically broadening or diminishing after some time. In contemplating and removing outline, it is essential to get a handle on the impact of de-inclining on the specter properties of the time strategy. This impact can be constellated by the rehash reaction of the de-floating point of confinement. 4.2.4.1

Recognizing Design: A Repeat Space Approach

ID of point of reference in a period technique is energetic in light of the way that model in an outline can be observed from low repeat risks. What looks like propensity out of a minimal time range strategy piece dependably winds up being a low-repeat change – maybe part of a cycle – in the more drawn out approach. From time to time, learning the physical framework helps in seeing the plan. For instance, an abatement of ring width of a tree with time is regularly inadequate on geometrical grounds: the yearly development of wood is being set down on a dependably developing farthest point. On the off chance that the extent of wood made every year levels off as the tree ages, the ring width would be required to decay. The “changed negative exponential” de-inclining bend for ring width is kept up by this information of the physical framework. Without a physical clarification behind a particular model, we have to depend upon true systems. Granger and Hatanaka give some data on poor clarification of model [13]. They find that we can’t separate between a true blue plan and a low rehash change, and give the running with guide: It has been discovered helpful by the creator to consider as “coast” for a situation of size n all frequencies under 1 (2) n, as these will all be monotonic developing if the stage is zero, yet it must be underlined this is a discretionary run the show. It might additionally be seen that it is difficult to test whether a game plan is stationary or not, given just a limited case, as any undeniable model in mean could ascend out of an extraordinarily low rehash. On the off chance that we apply the above thinking to a 500-year tree-ring plan, we would express that collection with period longer than twofold the representation size, or 1000 years, ought to be viewed as model. Another paper portrays “incline in suggest” as containing all rehash parts whose wavelength beats the length of the watched time game plan [13]. Cook et al. [14] propose “skim in infer” thought in giving proposals for de-slanting tree-ring information: Given the above significance of model in mean, another target measure for picking the ideal rehash reaction of an electronic filer is as per the going with. Select a half rehash reaction cutoff in years for the channel that partners some critical level of the strategy length, n. This is the %n control delineated in Shumway and Woollacott [15]. The results of [15] prescribe that the rate is 67% to 75% in light of utilizing the cubic smoothing spline as a moved channel. The %n preface guarantees that little lowrehash differentiate, which is resolvable in the sorted-out tree rings, will be lost in assessing and clearing the change slant. This model also has a tendency of sorts on account of the firm character of the low-pass channel assessments of the progression incline. It won’t offer all around affirmation and, really, will vary from time to time while having any kind of perfect reliability of fit.

120 4.2.4.2

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Fitting the Pattern

Four elective approaches to manage de-drifting are: 1. First differencing; 2. Twist fitting; 3. Mechanized filtering; 4. Piecewise polynomials. This portion is weighted seriously toward the piecewise polynomials approach, which is by and large used in dendrochronology. 4.2.4.3

First Differencing

A period plan that is non-stationary in mean (e.g., slant in the way) can be affected static method by taking the model to isolate. The control separate is the processing of the estimation of the procedure now and again t and t − 1: wt = xt − xt−1

(4.1)

where xt is the original time series and wt is the first-differenced series. If the series is nonstationarity in not just the mean but in the rate of change of the mean (the slope), stationarity can be induced by taking the second difference, or the first difference of the first difference: ut = wt − wt−1

(4.2)

Differencing has been applied in hydrology in the context of ARIMA (Autoregressive integrated moving average) modeling of streamflow series [16]. Salas reports that first differencing can be risky in hydrology since it tends to bring a false high-rehash combination into an arrangement. Anderson portrays differencing as an approach to managing removal of non-stationarity from time game plan with everything considered. As shown by Anderson, each powerful differencing will reduce the instability of the blueprint, yet at some point, higher-engineer differencing will affect advancement in change. Right when instability develops, the approach has been over-differenced. First differencing is unsatisfactory for time strategy whose level itself has importance, as the differenced game plan is basically simply a change in level start with one insight then onto the accompanying, paying little respect to the level itself. 4.2.4.4

Curve Fitting

If a period plan dynamically changes in level after some time, it looks good for consideration as an example for some direct limit of time itself. Sometimes the numerical sort of the example work has a stable start. For instance, a changed unfavorable exponential wind with a sensible beginning in the refinement in tree geometry with time has been utilized to discharge the “age trend” from ring-width strategy [19].

TIME SERIES, STATIONARY, TIME SERIES DECOMPOSITION, DE-TRENDING

121

All things considered, the most considered utilized breaking point of time used in de-slanting is the base squares-fit straight line, which treats arrange model. Simple linear regression is used to fit the model xt = a + bt + et

(4.3)

where xt is the critical experience strategy at time t, a is the regression constant, b is the regression constant, and et are the regression residuals. The trend is then described by gt =  a + bt (4.4) where gt is the trend,  a is the estimated regression constant, and b is the estimated regression coefficient. The advantage of the straight-line method is simplicity. The straight line may be unrealistic, however, in restricting the functional form of the trend. Other functions of t (e.g., quadratic) might be better depending on the type of data. 4.2.4.5

Digital Filtering

Another procedure for dealing with trend is to describe the trend as a linearly filtered version of the original series. The original series is converted to a smooth “trend line” by weighting the individual observations gt =

s 

at x(t+r)

(4.5)

r=−q

where xt is the original series, {ar } is a set of filter weights (summing to 1.0), and gt is the smooth trend line. The weights are from time to time symmetric, with s = q and aj = a−j . If the weights are symmetric and all equal, the filter is a simple moving average, which generally is not recommended for measuring trend [20-21]. 4.2.4.6

Piecewise Polynomials

An alternative to fitting a curve to the entire time series (curve fitting) is to fit polynomials of time to different parts of the time series. Polynomials used this way are called piecewise polynomials. The cubic smoothing spline is a piecewise polynomial of time, t, with the running with properties: The polynomial is cubic (t raised to the third power). A substitute polynomial is fit to each social affair of three fixations throughout the activity. The first and second helpers are constant at each point. The “spline parameter” chooses the adaptability and relies on the relative massiveness given to “smoothness” of the fitted bend, and “closeness of fit,” or how shut the fitted wind goes to the individual server farms.

122

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

Given the approximate values yi = g(xi ) + i of some supposedly smooth function g at data points x1 , .., xn and a measure δyi of the standard deviation of yi , the issue is to recoup as far as possible from the information. Let s(xi ) be the spline curve, or the approximation to the smooth function g. Following De Boor [20], the spline curve is derived by minimizing the quantity p

 N   yi − s(xi ) i=1

δyi

+ (1 − p)

xN



D2 s

2

(4.6)

x1

Overall limits for a given spline parameter p, is that the place D2 s recommends the second subordinate of s concerning time. The first term is similar to a sum-ofsquares of deviations. The second term encourages cadenced development duties (second helper). Minimizing Equation (4.6) establishes a compromise between staying close to the given data (first term) and obtaining the smoothest possible curve (second term). The decision of p, where p can connect from 0 to 1, depends upon those two targets being given the more crucial centrality. For p = 0, s is the base squares straight-line fit to the information. At the other sensational, p = 1, s is the cubic spline interpolate, and encounters every datum point. As p ranges from 0 to 1, the smoothing spline changes beginning with one outstanding then onto the following. The term δyi considers the differential weighting of server farms. Following recommendations of De Boor et al. [20], we utilize the default MATLAB weighting (1 for all center interests). 4.2.4.7

Frequency Response

The frequency response function describes how a linear system responds to sinusoidal inputs different frequencies [20-21]. The frequency response function has two components – the gain and the phase. The gain at a given frequency describes how the amplitude of a sinusoid at that frequency is damped or amplified by the system. The phase describes how a wave at that frequency is shifted in absolute time. In reference to a spline curve, the phase is zero, and the “frequency response” merely describes the gain, or the amplitude, of the response function. The input to the “system” in this case is the original time series; the output is the smoothed curve purported to represent the trend. The frequency response measures how strongly the spline curve would respond to or track a periodic component of a given frequency, should the time series have such a component. The amplitude of frequency response at a given frequency is the ratio of the amplitude of the sinusoidal component in the smoothed series (the spline curve) to the amplitude in the original time series. 4.2.4.8

Connection of Recurrence Reaction to Spline Parameter

The cubic smoothing spline has wound up being legitimately remarkable as a deinclining system in dendrochronology in light of the way that the spline is adaptable and reasonably connected with an expansive collection of sorts of “age trend” or “growth trend” found in tree-ring information. Utilization of the spline to dendrochronology was first proposed by Cook and Peters [1], who derived a numerical

TIME SERIES, STATIONARY, TIME SERIES DECOMPOSITION, DE-TRENDING

123

relationship between the rehash reaction of the spline and the spline parameter, p. The relationship is given by u(f ) = 1 −

1 1+

p(cos2πf +2) 6(cos2πf −1)2

(4.7)

where u(f ) is the amplitude of frequency response at frequency f, and p is the spline parameter as defined earlier. A plot of u(f ) against f shows the response of the spline to variations at different frequencies. For trend lines, such as the smoothing spline, this response is higher toward the low-frequency end of the spectrum. Cook and Peters [1] moreover chose a unique relationship for the spline parameter p as a function of the “50% frequency response,” the frequency at which the amplitude of the frequency response of the spline is 0.50. This relationship is given by: 6(cos2πf − 1)2 p= (4.8) cos2πf + 2 Given a desired 50% frequency response, you can use Equation (4.8) to compute the spline parameter. For example, say the desired 50% frequency response is at a period 100 years, corresponding to a frequency of 1/100. The desired spline parameter is p=

6(0.998 − 1)2 = 7.7927E −6 0.998 + 2

(4.9)

Call the MATLAB limits casps() with above spline parameter with respect to a given time plan, and it will yield the pertinently smoothed time game plan. 4.2.4.9

Evacuation of Pattern

Once a model line has been fit to the information, we can see that line as tending to the “precedent.” The ask for remains, how to clear the model? On the off chance that the model perceiving check strategy has seen a precedent line, two choices are open. First is to subtract the estimation of the model line from the vital information, giving a period game plan of residuals from the precedent. This “capability” choice is beguiling for its straightforwardness, and for giving a strong breakdown of the change: the new blueprint is in obscure units from the fundamental approach, and the aggregate total of squares of the important information can be conferred as the model total of squares despite the remaining total of squares. The “degree” elective is connecting with two or three sorts of information in light of how the degree is dimensionless, and the degree task tends to expel glide in change that may keep running with a slant in the mean. Tree-ring width is one such information make: refinement of ring width has a tendency to be high when the mean ring width is high, and low when the mean ring width is low. Degree de-inclining, for the most part, is only possible for nonnegative time strategy, and perils the effect of the de-slanted course of action to high qualities if the fitted precedent line approaches near zero. De-inclining has an unclear impact on the range from high-pass separating, in that the change at low frequencies is reduced concerning fluctuation at high rates.

124

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

The rehash reaction of the spline is high for those frequencies act like spline. In the subsequent clearing of the precedent line, these frequencies are for the most part removed. Rates at which the rehash reaction of the spline is high are like those at which the extent of the de-slanted arrangement is low. Exactly when all is said and done, and there are no more lessened frequencies, the size of the de-slanted course of action will be reduced concerning the size of the primary information. The more flexible spline, the higher the rehash will be affected by the de-inclining standardized range. In looking at strategy de-inclined by various systems, it is positive to plot the ambiguous of two or three de-floated game plans on a relative match of tomahawks. To help the perception of the relative impacts of de-floating on various wavelengths, the spectra are best plotted as an organized range for such examination. Review that the domain in which the area lies with respect to the change occur. The space under the organized range is equivalent to one. Along these lines, the dispersing of advancement with rehash for a strategy with differences can be promptly separated and organized spectra plotted on a practically identical figure. 4.2.4.10

Measuring the Significance of Pattern

A reasonable degree of the vital importance of precedent in a period strategy is the bit of exceptional contrast in the arrangement addressed by the fitted model line, which can be figured by var(et ) R2 = 1 − (4.10) var(xt ) where var(xt ) is the distinction in the foremost experience game plan, and var(et ) is the difference in the residuals from the model line. Equation (4.10) measures the centrality of the trend segment in a period strategy time game plan and can go from 0 for no criticalness to 1 if the course of action is an unadulterated precedent. 4.3

4.3.1

Autocorrelation, Test for Independence, Linear Autoregressive Models Autocorrelation

This section depicts a MATLAB program with a Graphical UI (GUI) to figure the parameters of the autocorrelation and the intraoral cross-relationship parts of binaural pennant in context of the sound-related identity demonstrate proposed by Ando and Raichel, which can outline the differing hypothetical attributes such as pitch, timbre, and the spatial impression. The autocorrelation work (ACF) [17, 49] has been used to delineate the essential qualities of talk and music hails and has been associated with favored sound field conditions to getting together corridors. Primarily, the envelope delay of the ACF is used to depict the favored necessary time concede opening the resounding time because the favored condition of room acoustics immovably depends upon the transient properties of the source signal. Also, the fine structures of the ACF, for instance, the defer time, and the plentifulness of the ACF peaks, have been used to depict the pitch

AUTOCORRELATION, TEST FOR INDEPENDENCE, LINEAR AUTOREGRESSIVE MODELS

125

and timbre observations [5, 6]. The intraoral cross-relationship work (IACF) of the sound field has been used to portray the unique spatial characteristics of soundtracks. Moreover, these ACF and IACF parameters have been used to depict normal uproars and the sound quality in light of the way that the multidimensional assessment of the signal ascribes interfaces with the distinctive theoretical attributes such as sound tendency, tumult, load, talk intelligibility and so forth. The data binaural indications of a WAVE configuration report are experienced in an A-weighting framework. By then the ACF and IACF are figured by a FFT method according to Wiener-Khinchin theory.1 These calculation parameters can be varied through the substance modify fields in the GUI window (Figure 4.6). Waveforms of the ACF and IACF at each running development and the passing assortments of the ACF and IACF parameters are shown in the GUI window to check the settings figured. The table of the settings can be conveyed as the surpass desires mastermind.

Figure 4.6

Output of wave configeration.

Figure 4.6 shows the Graphical UI of the program. On the left - Top to bottom: The characters for best to base, for example, waveform, running ACF parameters, running IACF parameters, and a slider bar which demonstrates the results of each running development. On the right -Top to bottom: Filename and testing repeat, table of the parameters at each running packaging, ACF (left, y-rotate is in the logarithmic scale) 1 https://en.wikipedia.org/wiki/Wiener%E2%80%93Khinchin

theorem

126

STATISTICAL ANALYSIS OF NETWORK DATA USING MATLAB

and IACF (right) waveform, starting setting parameters (joining between time, running development, most extraordinary slack, and the range to choose τ1 ), and the catches for “Load record,” “Figure,” and “Spare components.” 4.3.2

ACF and IACF Parameters

τ1 and ϕ1 : The concede time and the adequacy of the chief critical apex of the institutionalized ACF, relating to the pitch wisdom. The essential huge zenith of the institutionalized ACF is portrayed by the best in the range from the underlying zerocross to 30 ms of the put off time since 30 ms of the ACF concede time identifies with the lower repeat most distant purpose of the pitch figure shown in [48, 49]. An isolated signal with a lower center repeats underneath 100 Hz, at times giving an ACF peak with a concede longer than 30 ms. In such case, the essential best inside the possible most noteworthy concede time (200 ms is central for the e calculation depicted underneath) is distinguished. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

% fs: sampling frequency % acf is two dimensional (delay time % and the amplitude) % the first zero-cross For i=1:floor(tmax*fs); tg=I;break, end end %.................................................................. % peak within the maximum delay (tmax) %.................................................................. For i=tg:floor(tmax*fs)-1 If acf(i,2)>acf(i+1,2)&&acf(1,2)>acf(i-1,2) P_tau(i,[1 2])=acf(I,[1 2]); I_tau=find(p_tau(:,2)); P_tau=p_tau(i_tau,:); end end [phi1,i_tau]=max(p_tau(:,2)); Tau1=p_tau(i_tau,1); %.................................................................. %peak within 30 ms %.................................................................. For i=tg:floor(0.030*fs)-1 If acf(I,2)>acf(i+1,2)&& acf(I,2)>acf(i-1,2) P_tau(I,[1,2])=acf(I,[1 2]); I_tau=find(p_tau(:,2)); P_tau=p_tau(i_tau,:); End End [phi1,i_tau]=max(p_tau(:,2)); Tau1=p_tau(i_tau, 1);

AUTOCORRELATION, TEST FOR INDEPENDENCE, LINEAR AUTOREGRESSIVE MODELS

127

τe : The ten-percentile envelope spoil of the ACF, delineating the level of diligence of the signal. It is figured from backslide and extrapolation of the adjacent maxima of the fundamental bit of ACF. On account of a wide assortment of the basic ACF envelope decay, the iterative procedure, which picks the best-fit-backslide line among a couple of choices, is displayed. The point by guide framework toward getting τe by the iterative procedure is depicted in Granger. W ϕ(0): The fifty-percentile width of the ACF adequacy around the commencement of the defer time, relating to the timbre insight [6]. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

% peak detection % igacf id acf in the logarithmic % scale % delta is varied from 3-50 ms in [11] %.................................................................. For i=2:10 r_taue =lgacf(floor((i-1)*delta*fs)+1: floor(i*delta*fs),[1 2]); [p_taue(I,1ii]=max(r_taue(:,2)); P_taue(I,1)=r_taue(ii,1); End Index_taue=find(p_taue(:,2)); R=p_taue(index_taue,:); Reg0=polyfit(r(:,1),r(:,2),1; Taue-1000*(-10-reg0_(1,2))/reg0(1,1); %.................................................................. % correlation coefficient of the regression line which is the % criteria of the iterative method %.................................................................. Corr=-corrcoef(r(:,1),r(:,2)); For i=2:floor(tmax*fs)-1; If acf(I,2)abs(dx); if steep t=dx; dx=dy; dy=t; end %.................................................................. %the main algorithm goes here. %.................................................................. if dy==0 q=zeros(dx+1,1); else q=[0;diff(mod([floor(dx/2):-dy:-dy*dx+floor(dx/2)]’,dx))>=0]; end %.................................................................. %and ends here. %.................................................................. if steep if y1=trace(tauHat(:,i)*eta’)%C7 y(i)>=sum(xi(i,:))%C8 end cvx_end; end

File findCrlb.m: Returns CRLB (Cramer-RaoLowerBound) for a particular target and anchor placement. 1 2 3 4 5 6 7 8 9 10

%.................................................................. %% Returns CRLB for a particular target and anchor placement %.................................................................. function [crlb]=findCrlb(tau,mu,sigmasq,phiIndex,phi,alpha,beta,X) In=monteCarloInt(tau,mu,sigmasq,X); I=zeros(2); %iterate over first dimension in 2D plane for v=1:2 %iterate over second dimension in 2D plane

CASE STUDY 4: NODE LOCALIZATION IN WIRELESS SENSOR NETWORK

11 12 13 14 15 16 17 18 19 20 21 22

323

for r=1:2 Num=(phi(v,phiIndex)-alpha(v,:)).*(phi(r,phiIndex)-alpha(r,:)); Dem=(sum(((repmat(phi(:,phiIndex),1,length(alpha))-alpha).ˆ2),1)).ˆ2; %Terms of the Fisher Information Matrix I(v,r)=((10*beta)/(log(10)))ˆ2*In*sum(Num./Dem); end end %.................................................................. %CRLB from Fisher Information Matrix %.................................................................. crlb=sqrt(trace(Iˆ-1)); end

File findRSS.m: Returns the Received Signal Strength (RSS) at all target nodes in a WSN. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

%.................................................................. %% Returns the Received Signal Strength (RSS) at all target nodes % in a WSN %.................................................................. function[P,X]=findRSS(phi,alpha,P0,beta,d0,mu,sigmasq,tau) [˜,nNodes]=size(phi); [˜,nAnchors]=size(alpha); gm = gmdistribution(mu,sigmasq,tau); % rng(’default’); % For reproducibility d=zeros(nNodes,nAnchors); %.................................................................. %Distance between jth target and ith anchor %.................................................................. for i=1:nNodes d(i,:)=sqrt(sum((repmat(phi(:,i),1,nAnchors)alpha(:,1:nAnchors)).ˆ2)); end X = random(gm,nNodes*nAnchors); %Noise n = reshape(X,[nNodes,nAnchors]); %Path Loss Model P=P0-10*beta*log10(d./d0)+n; end

File monteCarloInt.m: Returns the value of Monte Carlo integration used in calculating the Fisher information matrix. 1 2 3 4 5 6 7 8 9 10 11

%.................................................................. %% Returns the value of monte-carlo integration used in calculating %% the fisher information matrix %.................................................................. function [In] = monteCarloInt(tau,mu,sigmasq,X) %Contains samples of noise from GMM n = sort(X); p1 = tau(1)*(1/(sqrt(2*pi*sigmasq(:,:,1)))) *exp(-(n-mu(1)).ˆ2/(2*sigmasq(:,:,1))); p2 = tau(2)*(1/(sqrt(2*pi*sigmasq(:,:,2)))) *exp(-(n-mu(2)).ˆ2/(2*sigmasq(:,:,2)));

324 12 13 14 15 16 17 18 19 20 21 22

CASE STUDIES AND SAMPLE CODES

%PDF of the GMM p=p1+p2; gradp1 = -p1.*(n-mu(1))/sigmasq(:,:,1); gradp2 = -p2.*(n-mu(2))/sigmasq(:,:,2); %PDF of the derivative of the GMM gradp=gradp1+gradp2; f=(gradp.*gradp)./p; In=mean(f)*range(n); end

The result:

Figure 8.10 (a) Simulated path loss model; (b) Histogram of simulated RSS noise modeled as Gaussian mixture.

Figure 8.11

RMSE vs N (number of anchors).

CASE STUDY 5: LEACH ROUTING PROTOCOL FOR A WSN

Figure 8.12

8.6

325

CDF vs error.

Case Study 5: LEACH Routing Protocol for a WSN

LEACH (Low energy adaptive clustering hierarchy) [11, 12, 14-17] is a hierarchical protocol in which most nodes transmit to cluster-heads, and the cluster-heads aggregate and compress the data and forward it to the base station (sink). Each node uses a stochastic algorithm at each round to determine whether it will become a clusterhead in this round. LEACH assumes that each node has a radio powerful enough to directly reach the base station or the nearest cluster-head, but that using this radio at full power all the time would waste energy. Nodes that have been cluster-heads cannot become cluster-heads again for P rounds, where P is the desired percentage of cluster-heads. Thereafter, each node has a 1/P probability of becoming a cluster-head in each round. At the end of each round, each node that is not a cluster-head selects the closest cluster head and joins that cluster. The cluster-head then creates a schedule for each node in its cluster to transmit its data.

Figure 8.13

Cluster formation in LEACH.

326

CASE STUDIES AND SAMPLE CODES

All nodes that are not cluster-heads only communicate with the cluster-head in a TDMA fashion, according to the schedule created by the cluster-head. They do so using the minimum energy needed to reach the cluster head, and only need to keep their radios on during their time slot. LEACH also uses CDMA so that each cluster uses a different set of CDMA codes, to minimize interference between clusters. As described earlier, the operation of LEACH consists of several rounds with two phases in each round. Working of LEACH starts with the formation of clusters based on the received signal strength. The algorithm for LEACH protocol is as follows: The first phase of LEACH is setup phase and the second is steady-state phase. Setup and steady-state are the two main phases in the protocol. In setup phase sensor nodes organize into local cluster where cluster-head is declared based on energy, probability function. Rule-based selection of cluster-head is done as follows:

T (n) =

⎧ ⎨ ⎩

p 1−p(r mod

, n∈G ) 0, otherwise 1 p

(8.1)

where p is desired percentage of cluster-heads, r is current round and G is set of sensor nodes which were not cluster-head for last 1/p rounds. The startup and setup phase algorithms for LEACH are as follows [18]:

Algorithm 8.1 Setup phase BEGIN Step 1. Start round r = 0; Step 2. All the sensor nodes have the probability of becoming clusterhead; Step 3. For round r, after node is elected as cluster-head, it will start broadcasting ’Hello’ message to nodes in a cluster; Step 4. Energy used to broadcast message is equal for all the clusterheads; Step 5. Initially, all the nodes that are not cluster-head are supposed to keep their receiver ON to receive broadcasted message; Step 6. For round r, non-cluster-head nodes will choose the cluster based on minimum energy criteria required to transmit/receive messages/data; Step 7. Random selection of cluster-head will be done if more numbers of nodes declare themselves as cluster-head. END

CASE STUDY 5: LEACH ROUTING PROTOCOL FOR A WSN

327

Algorithm 8.2 Steady-state phase BEGIN Step 1. Non-cluster-head node informs cluster-head about its presence in that cluster; Step 2. Cluster-head will have list of members in cluster due to step 1; Step 3. Cluster-head schedules communication of non-cluster-head nodes with itself based on TDMA; Step 4. The scheme is used to minimize power consumption in noncluster-head nodes. Transmitter is switched off; Step 5. Data aggregation is done by cluster-head after collecting data from non-cluster-head nodes; Step 6. Cluster-head finally transmits the same to base station. END

Figure 8.14

Steady-state phase in LEACH.

CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

close all; clear; clc; %.................................................................. % Network Establishment Parameters % Area of Operation % Field Dimensions in meters %.................................................................. xm=100; ym=100; % added for better display results of the plot x=0; % added for better display results of the plot y=0; % Number of Nodes in the field % n=100; % Number of Dead Nodes in the beggining % dead_nodes=0; % Coordinates of the Sink (location is predetermined in % this simulation) %

328 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

CASE STUDIES AND SAMPLE CODES

sinkx=50; sinky=200; %.................................................................. % Energy Values %%% % Initial Energy of a Node (in Joules) % %.................................................................. % units in Joules Eo=2; % Energy required to run circuity (both for transmitter and % % receiver) units in Joules/bit Eelec=50*10ˆ(-9); ETx=50*10ˆ(-9); ERx=50*10ˆ(-9); %.................................................................. % Transmit Amplifier Types %.................................................................. % units in Joules/bit/mˆ2 (amount of energy spent by the amplifier % to transmit the bits) Eamp=100*10ˆ(-12); % Data Aggregation Energy % EDA=5*10ˆ(-9); % units in Joules/bit % Size of data package % k=4000; % units in bits % Suggested percentage of cluster head % % a 5 percent of the total amount of nodes used in the network % is proposed to give good results p=0.05; % Number of Clusters % No=p*n; % Round of Operation % rnd=0; % Current Number of operating Nodes % operating_nodes=n; transmissions=0; temp_val=0; flag1stdead=0; %.................................................................. % End of Parameters % Creation of the Wireless Sensor Network % Plotting the WSN %.................................................................. for i=1:n % sensor’s ID number SN(i).id=i; % X-axis coordinates of sensor node SN(i).x=rand(1,1)*xm; % Y-axis coordinates of sensor node SN(i).y=rand(1,1)*ym; % nodes energy levels (initially set to be equal to "Eo" SN(i).E=Eo; % node acts as normal if the value is ’0’, if elected as % a cluster head it gets the value ’1’ (initially all nodes

CASE STUDY 5: LEACH ROUTING PROTOCOL FOR A WSN

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

329

% are normal) SN(i).role=0; % the cluster which a node belongs to SN(i).cluster=0; % States the current condition of the node. when the node is % operational its value is =1 and when dead =0 SN(i).cond=1; % number of rounds node was operational SN(i).rop=0; %rounds left for node to become available for ClusterHead election SN(i).rleft=0; % nodes distance from the cluster head of the cluster in % which he belongs SN(i).dtch=0; % nodes distance from the sink SN(i).dts=0; % states how many times the node was elected as a Cluster Head SN(i).tel=0; % round node got elected as cluster head SN(i).rn=0; %node ID of the cluster head which the "i" normal node belongs to SN(i).chid=0; hold on; figure(1) plot(x,y,xm,ym,SN(i).x,SN(i).y,’ob’,sinkx,sinky,’*r’); title ’Wireless Sensor Network’; xlabel ’(m)’; ylabel ’(m)’; end %.................................................................. % Set-Up Phase %.................................................................. while operating_nodes>0 % Displays Current Round % rnd % Threshold Value % t=(p/(1-p*(mod(rnd,1/p)))); % Re-election Value % tleft=mod(rnd,1/p); % Reseting Previous Amount Of Cluster Heads In the Network % CLheads=0; % Reseting Previous Amount Of Energy Consumed In the Network % on the Previous Round % energy=0; %.................................................................. % Cluster Heads Election %.................................................................. for i=1:n

330 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

CASE STUDIES AND SAMPLE CODES

% reseting cluster in which the node belongs to SN(i).cluster=0; % reseting node role SN(i).role=0; % reseting cluster head id SN(i).chid=0; if SN(i).rleft>0 SN(i).rleft=SN(i).rleft-1; end if (SN(i).E>0) && (SN(i).rleft==0) generate=rand; if generate< t % assigns the node role of acluster head SN(i).role=1; % Assigns the round that the cluster head was % elected to the data table SN(i).rn=rnd; SN(i).tel=SN(i).tel + 1; % rounds for which the node will be unable to become a CH SN(i).rleft=1/p-tleft; % calculates the distance between the sink and the cluster hea SN(i).dts=sqrt((sinkx-SN(i).x)ˆ2 + (sinky-SN(i).y)ˆ2); % sum of cluster heads that have been elected CLheads=CLheads+1; % cluster of which the node got elected to be cluster head SN(i).cluster=CLheads; % X-axis coordinates of elected cluster head CL(CLheads).x=SN(i).x; % Y-axis coordinates of elected cluster head CL(CLheads).y=SN(i).y; % Assigns the node ID of the newly elected cluster head to an array CL(CLheads).id=i; end end end % Fixing the size of "CL" array % CL=CL(1:CLheads); %.................................................................. % Grouping the Nodes into Clusters & caclulating the distance % between node and cluster head % %.................................................................. for i=1:n % if node is normal if (SN(i).role==0) && (SN(i).E>0) && (CLheads>0) for m=1:CLheads d(m)=sqrt((CL(m).x-SN(i).x)ˆ2 + (CL(m).y-SN(i).y)ˆ2); % % % % %

we calculate the distance ’d’ between the sensor node that is transmitting and the cluster head that is receiving with the following equation+d=sqrt((x2-x1)ˆ2+(y2-y1)ˆ2) where x2 and y2 the coordinates of the cluster head and x1 and y1 the coordinates of the transmitting node

CASE STUDY 5: LEACH ROUTING PROTOCOL FOR A WSN

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

331

end % fixing the size of "d" array d=d(1:CLheads); % finds the minimum distance of node to CH [M,I]=min(d(:)); % displays the Cluster Number in which this node belongs too [Row, Col] = ind2sub(size(d),I); % assigns node to the cluster SN(i).cluster=Col; % assigns the distance of node to CH SN(i).dtch= d(Col); SN(i).chid=CL(Col).id; end end %.................................................................. % Steady-State Phase %.................................................................. % Energy Dissipation for normal nodes %.................................................................. for i=1:n if (SN(i).cond==1) && (SN(i).role==0) && (CLheads>0) if SN(i).E>0 ETx= Eelec*k + Eamp * k * SN(i).dtchˆ2; SN(i).E=SN(i).E - ETx; energy=energy+ETx; % Dissipation for cluster head during reception if SN(SN(i).chid).E>0&&SN(SN(i).chid).cond==1&& SN(SN(i).chid).role==1 ERx=(Eelec+EDA)*k; energy=energy+ERx; SN(SN(i).chid).E=SN(SN(i).chid).E - ERx; % if cluster heads energy depletes with reception if SN(SN(i).chid).E