You are on page 1of 309

MATLAB:

Introductory Course
By

Prof. Gamal El-Sheikh

Cairo 2022
G.A. El-Sheikh MATLAB: Introductory Course i

Praise and Thanks be to ALLAH

To, in the name of ALLAH, my Father and Mother

To my wife and our daughters and sons

G.A. El-Sheikh
Cairo 2022

Copyright, 2022
The copyright of this book belongs to the author under the terms of the international
copyrights acts. 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, without written permission of the Author.

ISBN:

‫لحلول الطباعة المتكاملة‬


‫ الجيزة‬- ‫ بجوار رئاسة حي الدقي‬- ‫ بين السرايات‬- ‫ش السكري‬7
01124888835 - 01063177771

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
i
G.A. El-Sheikh MATLAB: Introductory Course ii

Preface
Computational Thinking is getting more and more attention, where it represents a universally
applicable attitude and skill set everyone, not just computer scientists, would be eager to learn
and use. Computational Thinking draws on math as its foundations in addition to enhanced
math problem solving ability and therefore, the readers/ trainee can focus more on
Computational Thinking instead of Computational Doing.

The breadth and depth of one’s mathematical knowledge might not match his or her ability to
solve mathematical problems or to analyze systems' performance. In today’s applied science
and applied engineering, one usually needs to get the mathematical problems at hand or
formulations solved efficiently in a timely manner without complete understanding of the
numerical techniques involved in the solution process. Therefore, it can be considered as a
trend to focus more on how to formulate the real problem in a form suitable for computer
solution and on the interpretation of the results generated from that computer. Furthermore,
even without a complete preparation of mathematics, it is possible to solve some advanced
mathematical problems using a computer. Consequently, this text is useful for those who
frequently feel that their level of math preparation is not high enough because they still can
get their math problems at hand solved with the encouragement gained from its reading.

MATLAB (MATrix LABoratory) is developed by the MathWorks Inc. to integrate


computation, visualization, and programming in a flexible and open environment. It offers
engineers, scientists, and mathematicians an intuitive language for expressing problems and
their solutions mathematically and graphically. Complex numeric and symbolic problems can
be solved in a fraction of the time required with a programming language such as C, C++,
FORTRAN, Java or visual versions.

MATLAB is an interactive system for doing numerical computations and it relieves you with
a lot of the mundane tasks associated to solving problems numerically. In addition, MATLAB
is equipped with online help facility or documentation. This allows you to spend more time
thinking, and encourages you to experiment. MATLAB makes use of highly respected
algorithms and hence you can be confident about your results. Powerful operations can be
performed using just one or two commands. You can build up your own set of functions for a
particular application. Excellent graphics' facilities are available, and the pictures can be
inserted into different documents. MATLAB had made contributions to the mathematics,
engineering, and scientific community in different disciplines and is equipped with excellent
online help facility or documentation.

Therefore, the book is devoted to Familiarization with MATLAB and SIMULINK with
application examples in addition to m-files (script or function) creation and execution. Entry
of data (numbers, characters, logical), vectors, matrices, polynomials and transfer functions in
addition to different operations concerning each of these entries. Matrix operations include
transpose, addition, inversion and egienvalues. Plotting of different types of data with axes'
labels and figure's caption in addition to keys for different curves. Loading /saving data
from/into files with link into any type of processing. Link between the MATLAB and
SIMULINK including transfer of data between them and running.

The MATLAB environment allows the user to:


 manage variables
 import and export data

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
ii
G.A. El-Sheikh MATLAB: Introductory Course iii

 generate data, especially the random with pre-specified steps and sequence length.
 perform calculations
 generate plots
 develop and manage files for use with MATLAB.

At the end of this study, the applicant/Engineer should


 access and be familiar with the MATLAB, and SIMULINK.
 introduce the concept of mathematical programming using the MATLAB.
 understand what is meant by simulation and design packages/tools; mainly the
MATLAB, SIMULINK and its constituents
 study how to define variables, matrices etc, how to plot results and write simple
MATLAB codes.
 simulate and evaluate the performance of a process with a certain configuration
 able to create and run m-files (script or function) for a certain project or case study
 evaluate the difference between analytic and numerical methods for solving differential
equations.

Programming with MATLAB


This text is devoted to provide an introduction and overview of how MATLAB's calculator
mode is used to implement interactive computations. In addition, learning how to write M-file
programs (script or function) to implement numerical methods; more specific objectives and
topics include,
 Learning how real and complex numbers are assigned to variables
 Learning how vectors and matrices are assigned values using simple assignment, the
colon operator, and the linspace and logspace functions.
 Understanding the priority rules for constructing mathematical expressions.
 Gaining a general understanding of built-in functions and how you can learn more about
them with MATLAB Help facilities.
 Learning how to use vectors to create a simple line plot based on an equation.
 Learning how to create well-documented M-files in the edit window and invoke them
from the command window.
 Understanding the difference between script and function files.
 Understanding how to incorporate help comments in functions.
 Knowing how to set up M-files so that they interactively prompt users for information
and display results in the command window.
 Essentials of MATLAB Programming, Solving Calculus Problems and Solving Linear
Algebra Problems
 Understanding the role of subfunctions and how they are accessed.
 Knowing how to create and retrieve data files.
 Learning how to write clear and well-documented M-files by employing structured
programming constructs to implement logic and repetition.
 Recognizing the difference between (if...elseif) and switch constructs.
 Recognizing the difference between (for...end) and while structures.
 Knowing how to animate MATLAB plots.
 Understanding what is meant by vectorization and why it is beneficial.
 Understanding how anonymous functions can be employed to pass functions to function
function M-files.
 Types of errors with analysis including Roundoff and Truncation Errors.

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
iii
G.A. El-Sheikh MATLAB: Introductory Course iv

MATLAB is a powerful, comprehensive, user-friendly, and interactive software package that


is gaining acceptance as the ideal computational choice for scientists and engineers and is
becoming an industrial standard, used to solve a wide range of problems in other diverse areas
such as economics, business, technology, engineering, science, and education.

The reason that MATLAB had replaced other technical computational languages is that
MATLAB is based on simple and easy-to-use programming tools, graphic facilities, built-in
functions, and an extensive number of toolboxes.

Remember that no one can learn a programming language by only reading the language
construct or syntax. It necessitates programming practice and writing your own code while
studying those of others. Therefore, each chapter presents some assignments to be practiced
and to study the solutions presented towards modifications of your personnel towards
maturing.

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
iv
G.A. El-Sheikh MATLAB: Introductory Course v

Table of Contents
1- Familiarization with MATLAB and SIMULINK 1
1.1 General
1.2 MATLAB and SIMULINK
1.3 The MATLAB Product Family
1.4 MATLAB Toolboxes
1.5 How to Run/Quit MATLAB
1.6 Batch Jobs/Processes
1.7 Suggestions concerning the MATLAB programming
1.8 Getting Started 10
1.9 Entering and Running MATLAB
Start Up
Online Help
1.10 Variables
Variable Assignment
Active Variables
Removing a Variable
Saving and Restoring Variables
Variable Arithmetic
Double Precision Arithmetic
Command-Line Editing
1.11 Miscellaneous Features and Programming Issues 14
Programming Suggestions
Built-In Mathematical Functions
1.12 Controlling Command Window Input and Output 16
1.13 Programming Style and Goodness of Programs 18
1.13.1 Elements of Good Style
1.13.2 Good Programming Style
1.13.3 Tips for Improving the Readability of your Code
1.14 Miscellaneous MATLAB Features 21
1.15 Data Types 24
1.16 Operator Precedence 26
1.17 Exercises-01 27

2- Vectors and Matrices 28


2.1 Vectors 28
2.2 Matrices 29
2.3 Built-In Matrix Functions 29
2.3.1 Matrices of Random Entries
2.3.2 Magic Squares
2.3.3 Matrices of Ones
2.3.4 Matrices of Zeros
2.3.5 Diagonal Matrices
2.4 Defining Matrices in MATLAB 32
2.5 Engineering Application of Matrices 34
2.6 Subscripting and Indexing 35
2.6.1 Accessing Single Elements of a Matrix
2.6.2 Accessing Multiple Elements of a Matrix
2.6.3 Expanding the Size of a Matrix
2.6.4 Deleting Rows and Columns

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
v
G.A. El-Sheikh MATLAB: Introductory Course vi

2.6.5 Concatenating Matrices


2.6.6 Advanced Indexing
2.6.7 Indexing Into Multidimensional Arrays
2.6.8 Building Matrices from Block
2.7 Matrix Operations 39
2.7.1 Matrix Transpose
2.7.2 Matrix Addition/Subtraction
2.7.3 Matrix Multiplication
2.7.4 Matrix Inversion
2.7.5 Matrix Functions "any" and "all"
2.7.6 Returning more than One Value
2.7.7 Round Floating Point numbers to Integers
2.7.8 Matrix-Element Level Operations
2.7.9 Sub-Matrices
2.8 Empty Matrices 44
2.8.1 Operating on an Empty Matrix
2.8.2 Using Empty Matrices with If or While
2.9 Exercises-02 46

3- Polynomials in MATLAB 48
3.1 Polynomial Function Summary
3.2 Representing Polynomials
3.3 Polynomial Roots
3.4 Polynomial Evaluation
3.5 Convolution and Deconvolution
3.6 Polynomial Derivatives
3.7 Partial Fraction Expansion
3.8 Exercises-03 53

4- Systems of Linear Equations 54


4.1 Solution of Linear Equations
4.2 Example-4.1
4.3 Example-4.2
4.4 Exercises-04 57

5- MATLAB m-Files 58
5.1 Constructing a Program in MATLAB
5.2 Program Development with M-Files
5.2.1 Example-5.1
5.2.2 Example-5.2
5.2.3 M-File Examples
5.2.4 Scripts
5.3 Function Files
5.4 Batch Jobs
5.5 Detailed Functions 67
5.5.1 Simple Function Example
5.5.2 Basic Parts of a Function M-File
5.5.3 Function Name
5.5.4 How Functions Work

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
vi
G.A. El-Sheikh MATLAB: Introductory Course vii

5.5.5 Checking the Number of Function Arguments


5.5.6 Passing Variable Numbers of Arguments
5.5.7 Local and Global Variables
5.6 Exercises-05 75

6- Flow Control Structures 77


6.1 Colon Notation
6.2 Relational and Logical Constructs
6.3 Branching Constructs
6.3.1 If-end Construct
6.3.2 If-else-end Construct
6.3.3 If-elseif-end Construct
6.3.4 Switch and Case
6.4 Looping Constructs
6.4.1 For Loops
6.4.2 While Loops
6.4.3 Break
6.4.4 Continue
6.4.5 try ... catch
6.4.6 return
6.4.7 Recursion
6.5 Exercises-06: Flow Control 92

7- Character Arrays (Strings) 95


7.1 General
7.2 Character Arrays
7.2.1 Creating Character Arrays
7.2.2 Creating Two-Dimensional Character Arrays
7.2.3 Converting Characters to Numeric Values
7.3 Cell Arrays of Strings
7.3.1 Converting to a Cell Array of Strings
7.3.2 String/Numeric Conversion
7.4 String Comparisons
7.4.1 Comparing Strings for Equality
7.4.2 Comparing for Equality Using Operators
7.4.3 Categorizing Characters within a String
7.5 String Searching and Replacing
7.6 String Evaluation
eval
Constructing Strings for Evaluation
feval
7.7 Exercises-07 104

8- Graphics 106
8.1 Two-Dimensional Plots
8.2 Two-Dimensional Contour Plots
8.3 Cartesian or X-Y Plots
8.4 Polar Plots 111
8.5 Multiple Plots
8.6 Plotting Data Points with Declarations

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
vii
G.A. El-Sheikh MATLAB: Introductory Course viii

8.7 Printing Graphic Plots


8.8 Three-Dimensional Graphics
8.9 BAR and Histogram Graphs
8.10 Creating Hexagonal Cell in MATLAB 129
8.11 Animations 162
8.12 Simulation 166

9- Dates and Times 188


9.1 Date Formats
Types of Date Formats
Conversions between Date Formats
Date String Formats
9.2 Output Formats
Current Date and Time
9.3 Calendar Calculation Problems 192
9.4 Exercise-09 203

10- Solving Ordinary Differential Equations (ODE) 207


10.1 Introduction 207
10.2 Solving one ODE
10.3 Solving two ODE’s simultaneously
10.4 Newton-Raphson Method MATLAB Program 214

11- Errors and Warnings 225


11.1 Error Handling with eval and lasterr
11.2 Displaying Error and Warning Messages

12- Creating a GUI in Matlab 227


13- Revision: MATLAB Computer Sessions 232

14- Real World Applications 243


14.1 Example-14.1: Temperature Conversion
14.2 Example-14.2: Free Vibration Response of Undamped SDOF System
14.3 Example-14.3: Statistical Analysis of Experimental Data
14.4 Example-14.4: Least Squares Analysis of Geological Borings
14.5 Example-14.5: Steady State Temperature in a Chimney Cross Section
14.6 Example-14.6: Matrix Arithmetic
14.6.1 Matrix Addition
14.6.2 Matrix Multiplication
14.7 Example-14.7: Use Bisection Method to Compute Zeros of a Function
14.8 Example-14.8: Sorting 264

15- MATLAB Lab Assignments 267


15.1 Variable, Operator and Expression
15.2 Library Function
15.3 Single Dimension Array
15.4 Two Dimension Array
15.5 General 271

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
viii
G.A. El-Sheikh MATLAB: Introductory Course ix

16- Some of the General Purpose Commands 274

References 294

mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
ix
G.A. El-Sheikh MATLAB: Introductory Course 1

1- Familiarization with MATLAB and SIMULINK


1.1 General
Design methods in control usually comprise a synthesis procedure (sometimes with specific
numerical calculation routines) followed by a performance assessment procedure (using a
time domain simulation or frequency response plot). Consequently the control engineer needs
easy and flexible access to a set of powerful analysis and synthesis tools like:
1. specialized plots (Bode, Nichols, Nyquist, Inverse Nyquist),
2. specialized numerical routines (Riccati equation solvers, Diophantine equation solvers) and
3. simulation routines (time domain plots).
In addition, the design procedure itself is often a free and interactive path between these
various routines and their utilities controlled and directed by the control engineer.

For system simulation, there are a variety of tools that have different characteristics
concerning its complexity, ease to use and capabilities, other than the known high level
languages: FORTRAN, C, BASIC. The main tools are the Advanced Continuous Simulation
Language (ACSL), EASY5, Matrix Laboratory (MATLAB) family, MATRIXx family and
SIMNON. These simulation tools integrate the following basic functions:
1. Representation of mathematical models within the simulation tool environment
either using structured simulation language (ACSL and SIMNON) or block
diagram form (MATLAB-SIMULINK, MATRIXx, EASY5).
2. Simulation of dynamic response to selected input stimuli.
3. Graphics capability to analyze the results from simulation.
4. Error detection and debug facility.
5. User communication in friendly and easy way.

The simulations' tools should have some essential requirements as follows:


1. Capable of emulating real systems that have different attributes such as:
 large scale, consisting of many components interacting in a complex fashion.
 multivariable
 nonlinear
 hybrid systems that contain continuous as well as discrete elements
 multirate in discrete time
 discontinuous
2. Block diagram facility including block nesting for hierarchical system representation.
3. Equation based modeling
4. High level code insertion facilities
5. Interactive simulation capabilities
6. Graphics capability
7. Fast run time
8. User friendly through:
 well documented
 easy to access/edit package functions
 error detection and debugging facilities
 good access to program suppliers
9. Reasonable platform costs

mat1-01-int
1
G.A. El-Sheikh MATLAB: Introductory Course 2

There are some desired requirements that the simulations' tools should have as follows:
1. Availability of design tools in the following areas, that may be valuable to any research
work:
 matrix computation facilities
 time/frequency response analysis
 stability and sensitivity analysis
 optimization techniques and equilibrium point determination
 signal processing
 systems model identification, transformation, reduction and linearization
 robust and optimal control philosophies
2. Access to different types of libraries
3. Facility to convert from a block diagram representation to high level language source code
suitable for compilation
4. Automatic generation of real-time code to facilitate the hardware-in-loop testing of control
designs generated from the research and leading to a functional prototype.
5. Animated interactive simulation capability to allow the inclusion of animated manual
control panels that can be used during the simulation. Model inputs and parameters may be
altered via animated switches, dials, sliders, etc. whilst the simulation is running. The good
example for this application is that a simulated aircraft can be flown with animated
controls whilst height, orientation, velocity, and acceleration are all monitored via the
animated instruments.
6. On line help facility to access the help index at the computer terminal, provide hints,
provide warnings, provide error messages, etc.
7. Capability to operate on both workstations and PC computer platforms with provision for
easy transfer of models and data between platforms.
8. Customized icon creator/editor

1.2 MATLAB and SIMULINK


Matlab is a commercial "Matrix Laboratory" package which operates as an interactive
programming environment. It is a mainstay of the Mathematics Department software lineup
and is also available for PC's and Macintoshes and may be found on the CIRCA VAXes.
Matlab is well adapted to numerical experiments since the underlying algorithms for Matlab's
builtin functions and supplied m-files are based on the standard libraries LINPACK and
EISPACK.

Matlab program and script files always have filenames ending with ".m"; the programming
language is exceptionally straightforward since almost every data object is assumed to be an
array. In addition, graphical output is available to supplement numerical results and online
help is available from the Matlab prompt (>>), both generally (listing all available
commands):
>> help
[a long list of help topics follows]
and for specific commands:
>> help fft
[a help message on the fft function follows].

Matlab is an interactive program for numerical computation and data visualization; it is used
extensively by control engineers for analysis and design. There are many different toolboxes
available which extend the basic functions of Matlab into different application areas. Matlab

mat1-01-int
2
G.A. El-Sheikh MATLAB: Introductory Course 3

is supported on Unix, Macintosh, and Windows environments; a student version of Matlab is


available for personal computers.

MATLAB and SIMULINK are interactive programs designed to perform scientific and
engineering numerical computations. The MATLAB is a powerful yet easy to use system for
interactive numeric computation, data analysis, and graphics with applications in following
subjects:
1. Control Design, Simulation and Analysis
2. Electrical and electronic engineering
3. Mechanical engineering
4. Civil engineering
5. Applied mathematics
6. Geology/Geographic
7. Acoustics/Speech Analysis
8. Physics
9. Economics
10.Communications engineering
11.Satellite communications
12.Robotics

It can be run on a wide range of computers including PCs, Macintoshes, Workstations, and
Industrial Computers. MATLAB has application Toolboxes that add specific functions for
control system design, system identification, digital signal processing, image processing,
symbolic functions, system optimization, neural networks, fuzzy approach, SIMULINK, data
acquisition, multivariable frequency domain design and analysis, -analysis and synthesis.

The powerful feature of MATLAB is achieved in two ways; the first is through using m-files
to create new commands from existing built-in functions and other m-files. The second is
through the mex-interface allowing C and FORTRAN subroutines to be dynamically linked to
the MATLAB environment.

This tutorial is devoted to help you get started with MATLAB as a simulation tool and clarify
how MATLAB can be used in the solution of engineering problems as a CAD tool.
Throughout this tutorial it is assumed that you will have access to supplementary material on
matrices, matrix arithmetic/operations, and linear algebra.

mat1-01-int
3
G.A. El-Sheikh MATLAB: Introductory Course 4

1.3 The MATLAB Product Family


This paper highlights how the MathWorks products fit together.

MATLAB is the foundation for all the MathWorks products. MATLAB combines numeric
computation, 2-D and 3-D graphics, and language capabilities in a single, easy-to-use
environment.
MATLAB Extensions
MATLAB Extensions are •MATLAB Compiler
optional tools that support MATLAB •MATLAB C/C ++ Math Libraries
the implementation of •MATLAB Web Server
systems developed in •MATLAB Report Generator
MATLAB.
SIMULINK
Toolboxes
•Control System
•Communications
Simulink Extensions •Database
•Financial
•Simulink Accelerator •Frequency Domain System Identification
•Real-Time Workshop •Fuzzy Logic
•Real-Time Windows Target •Higher-Order Spectral Analysis
•Stateflow® •Image Processing
•LMI Control
Blocksets •Model Predictive Control
•DSP •mu-Analysis and Synthesis
•Fixed-Point •NAG ® Foundation
•Nonlinear Control Design •Neural Network
•Power Systems •Optimization
•Partial Differential Equation
•QFT Control Design
•Robust Control
•Signal Processing
•Spline
•Statistics
•Symbolic Math
•System Identification
•Wavelet

Toolboxes are libraries of MATLAB functions that customize MATLAB for solving
particular classes of problems. Toolboxes are open and extensible; you can view
algorithms and add your own.

Simulink is a system for nonlinear simulation that combines a block diagram interface and “live”
simulation capabilities with the core numeric, graphics, and language functionality of MATLAB.

Simulink Extensions are optional tools that support the implementation of systems developed in
Simulink.

Blocksets are collections of Simulink blocks designed for use in specific application areas.

mat1-01-int
4
G.A. El-Sheikh MATLAB: Introductory Course 5

1.4 MATLAB Toolboxes


You can view the MATLAB code for any of the Toolboxes’ functions. You can change the
way any toolbox function works by copying and renaming the M-file, then modifying your
copy. You can also extend the toolbox by adding your own M-files. MATLAB Toolboxes
generally consist of a collection of m-files that implement application-specific commands as
follows:

1. Control Systems Toolbox provides functions for common control system design,
modeling, and analysis. In addition, time and frequency responses, root locus measures and
gain selection designs are supported in both continuous and discrete time. State space and
transfer function (polynomial) models are accommodated with tools for conversion
between different representations. That is, it provides tools for control engineering and
system theory to be implemented with transfer functions and state-space representations in
both continuous and discrete systems.

2. Model Predictive Control Toolbox provides tools for a particular approach to control
design, especially those applications involving constraints on the manipulated and/or
controlled variables. It is recommended to be combined with the control system toolbox.

3. Non-Linear Control Systems Design Toolbox operates with MATLAB, SIMULINK, and
Optimization Toolbox to provide a powerful optimization based technique for designing
optimal linear and non-linear control systems design, modeling, and analysis.

4. Robust Control Toolbox designed to be used in conjunction with the Control System
Toolbox to provide algorithms for advanced or robust control techniques such as LQG
based optimal control synthesis, H 2 and H  optimal control synthesis, singular value
based model reduction, spectral factorization and model building. These techniques are
utilized with single-input-single-output systems as well as multivariable feedback control
systems design.

5.  - Analysis and Synthesis Toolbox is another toolbox for advanced or robust control
design and analysis/synthesis with many capabilities. It has a collection of MATLAB m-
files that provides functions for the analysis and design of robust, linear control systems
using the  - Analysis and Synthesis technique and H  optimal control synthesis with
singular value decomposition techniques.

6. Multivariable Frequency Domain Toolbox provides functions for frequency domain


analysis of Multi-Input-Multi-Output (MIMO) systems. It deals with continuous and
discrete time systems, including ones with transport delay as well as non-square plants. It
can be used to provide 3-D arrays of data and its plotting.

7. Quantative Feedback Theory (QFT) Toolbox


The QFT Control Design Toolbox is a collection of MATLAB functions for designing robust
feedback systems using Quantitative Feedback Theory. The QFT is an engineering method
devoted to the practical design of feedback systems. It uses frequency domain concepts to
satisfy performance specifications and to handle plant uncertainty. The QFT Control
Toolbox includes a convenient GUI that facilitates loop shaping for the formulation of
simple, low-order controllers to meet design requirements.

mat1-01-int
5
G.A. El-Sheikh MATLAB: Introductory Course 6

8. Signal Processing Toolbox provides tools for digital signal processing and time-series
analysis. It is composed of a collection of algorithms that implement common filtering and
spectrum estimation techniques. It has functions for Fast Fourier Transform (FFT)
processing, filter design and analysis, parametric modeling and power spectrum estimation.

9. Image Processing Toolbox builds on MATLAB’s numeric, signal processing and


visualization capabilities to provide comprehensive system for image analysis and
algorithm development.

10.Hi-Spec Toolbox is a module for use with the MATLAB and contains specialized tools
for signal processing with higher order spectra.

11.System Identification Toolbox is an analysis module that contains tools for building
mathematical models, either off-line or on-line, of dynamical systems, based on observed
input-output data. It provides both a useful platform for teaching system identification and
advanced tools for practical model construction. It includes the most common parametric
and non-parametric techniques for identification and estimation with outputs (estimated
models) compatible with the Control System Toolbox. In addition, there are state space
identification functions used to identify just the unknown parameters of a partially
unknown system while preserving the essential physics of the system.
There are separate modules for the estimation of continuous-time state-space models from
observed input-output data.

12.Frequency Domain System Identification Toolbox contains specialized tools for the
identification of linear dynamic systems from measurements of the systems excitation and
frequency response. This toolbox is a collection of frequency domain system identification
procedures, covering the whole identification process from excitation signal design,
through data preprocessing, parameter estimation, graphics presentation of the results, to
model verification.

13.Neural Network Toolbox designed to be used for designing and simulating artificial
neural networks through different learning rules, transfer functions, and training strategies
in addition to design procedures required to implement the Neural Network. That is, this
toolbox makes, in conjunction with the MATLAB facilities, the Neural Network
technology more accessible to researchers, engineers, and scientists.

14.Fuzzy Logic Toolbox


The Fuzzy Logic Toolbox is a collection of functions built on the MATLAB ® numeric
computing environment. It provides tools for you to create and edit fuzzy inference
systems within the framework of MATLAB, or if you prefer you can integrate your fuzzy
systems into simulations with Simulink ®, or you can even build stand-alone C programs
that call on fuzzy systems you build with MATLAB. This toolbox relies heavily on
graphical user interface (GUI) tools to help you accomplish your work, although you can
work entirely from the command line if you prefer.

15.Optimization Toolbox designed to support linear and non-linear programming and


quadratic optimization techniques. It contains routines that implement the most widely
used methods for performing minimization and maximization on general nonlinear
functions. These routines include constrained and unconstrained optimization, least
squares, minimax and multi-objective optimization.

mat1-01-int
6
G.A. El-Sheikh MATLAB: Introductory Course 7

16.Spline Toolbox contains tools for the construction and use of piecewise polynomial
functions. It has a collection of MATLAB functions that implements the essential
programs of the B-spline package.

17.High order Statistics Toolbox builds on the computational and graphics capabilities of
MATLAB to provide statistical data analysis, modeling, and Monte Carlo Simulation.

18.Symbolic Toolbox adds to MATLAB’s integrated symbolic mathematics and variable


precision computation based on Maple V, with special libraries.

19.Data Acquisition Toolbox is a combination of hardware and software designed to be used


with MATLAB for collecting real-time data directly into the MATLAB workspace.

20.SIMULINK is a program built in the MATLAB and used to design, simulate, and analyze
dynamic systems from a block diagram description. It also provides a number of non-linear
blocks including relays, saturation, hysteresis, and transport delays. That is, it facilitates
the modeling and analysis of dynamic systems, including linear, nonlinear, continuous,
discrete and hybrid model types.

21.Block Diagram allows the user of the MATLAB and Control System Toolbox to transfer
a system given in block diagram form and of any degree of complexity into the equivalent
state space form.

22.The Database Toolbox provides a robust set of m-file functions enabling data to be
imported to and exported from databases within MATLAB.

23.Statistics Toolbox
The Statistics Toolbox is a collection of tools built on the MATLAB numeric computing
environment. The toolbox supports a wide range of common statistical tasks, from random
number generation, to curve fitting, to design of experiments and statistical process
control. The toolbox provides two categories of tools: (1) Building-block probability and
statistics functions and (2) Graphical, interactive tools. The first category of tools is made
up of functions that you can call from the command line or from your own applications.
Many of these functions are MATLAB M-files, series of MATLAB statements that
implement specialized Statistics algorithms. Secondly, the toolbox provides a number of
interactive tools that let you access many of the functions through a graphical user
interface (GUI). Together, the GUI-based tools provide an environment for polynomial
fitting and prediction, as well as probability function exploration.

24.Flight Dynamics and Control Toolbox


This toolbox is a collection of tools built on the MATLAB

There are many Toolboxes that can be used within the MATLAB environment to solve
different disciplines problems with any degree of complexity. In addition, you can create
your own toolbox to solve problems in the fields of your interest.

mat1-01-int
7
G.A. El-Sheikh MATLAB: Introductory Course 8

1.5 How to Run/Quit MATLAB


 To bring up MATLAB from the operating system prompt or running it either by typing
matlab or clicking its icon will present the following prompt
>>
If you are using the X Window system on the workstations then you can also start
MATLAB from the Main Menu by selecting "matlab" from the "Math Applications"
submenu. A window should pop up and start MATLAB. When you run MATLAB
under the window system, whether you start from the menu or a system prompt, a
small MATLAB logo window will pop up while the program is loading and disappear
when MATLAB is ready to use.

 The answer to the most popular question concerning any program is this: leave a Matlab
session by typing
>> quit
or by typing
>> exit
to the Matlab prompt.

 If you get stuck on what a command means; just type


>> help <command name> RET
Then try the command again. You do need to know the name of the command that you
are looking for; a list of all the commands can be found at the beginning of each
reference manual from the MATLAB documentation.
The designation RET means that you should type the "return" key; this is implicit after
a command.

 To get the benefits of your time, you should record the outcome of the commands
and experiments in a notebook.

1.6 Batch Jobs/Processes


Matlab is most often used interactively, but "batch" or "background" jobs can be performed as
well. Debug your commands interactively and store them in a file (script.m). To start a
background session from your input file and to put the output and error messages into another
file (script.out), enter this line at the system prompt:
nice matlab < script.m >& script.out &

You can then do other work at the machine or logout while Matlab grinds out your program
and the explanation of the sequence of commands above can be as follows:
1. The "nice" command lowers matlab's priority so that interactive users have first crack
at the CPU. You must do this for noninteractive Matlab sessions because of the load
that number; crunching puts on the CPU.
2. The "< script.m" means that input is to be read from the file script.m.
3. The ">& script.out" is an instruction to send program output and error output to the
file script.out. (It is important to include the first ampersand (&) so that error messages
are sent to your file rather than to the screen; if you omit the ampersand then your
error messages may turn up on other people's screens and your popularity will
plummet.)
4. Finally, the concluding ampersand (&) puts the whole job into background.

mat1-01-int
8
G.A. El-Sheikh MATLAB: Introductory Course 9

Of course, the file names used above are not important; these are just examples to illustrate
the format of the command string.

1.7 Suggestions concerning the MATLAB Programming


These are a few pointers about programming and programming in MATLAB in particular.
1) Try to utilize the indented style that you have seen in the above programs. It makes the
programs easier to read, the program syntax is easier to check, and it forces you to think
in terms of building your programs in blocks.
2) Put lots of comments in your program to tell the reader in plain English what is going on.
Some day that reader will be you, and you will wonder what you did.
3) Put error messages in your programs like the ones above. As you go through this manual,
your programs will build on each other. Error messages will help you debug future
programs.
4) Always structure your output as if it will be the input of another function. For example, if your program has
"yes-no" type output, do not have it return the words "yes" and "no," rather return 1 or 0, so that it can be
used as a condition for a branch or while loop construction in the future.
5) In MATLAB, try to avoid loops in your programs. MATLAB is optimized to run the built-
in functions. For a comparison, see how much faster A*B is over mult(A,B). You will be
amazed at how much economy can be achieved with MATLAB functions.
6) If you are having trouble writing a program, get a small part of it running and try to build
on that. With reference to 5), write the program first with loops, if necessary, then go
back and improve it.

mat1-01-int
9
G.A. El-Sheikh MATLAB: Introductory Course 10

1.8 Getting Started


MATLAB, the "MATrix LABoratory" program, was initially written with the objective of
providing scientists and engineers with interactive access to the numerical computation
libraries Linpack and Eispack. These libraries are carefully tested, high-quality programming
packages for solving linear equations and eigenvalue problems. MATLAB enables scientists
and engineers to use matrix-based techniques to solve problems, without having to write
programs in traditional languages like C and Fortran.

Nowadays MATLAB is a commercial "Matrix Laboratory" package which operates as an


interactive programming environment with graphical output. The MATLAB programming
language is exceptionally straightforward since almost every data object is assumed to be an
array. Hence, for some areas of engineering MATLAB is displacing the Fortran and C
programming languages, due to its interactive interface, reliable algorithmic foundation, fully
extensible environment, and computational speed. MATLAB is available for many different
computer systems, including Macs, PCs and UNIX platforms.

The purposes of this course are two-fold; In addition to helping you get started with
MATLAB, we want you to see how MATLAB can be used in the solution of engineering
problems. The latter objective is achieved through the presentation of a series of engineering
application problems. Throughout this course we assume that you will have access to
supplementary material on matrices, matrix arithmetic/operations, and linear algebra.

1.9 Entering and Running MATLAB


Start Up
MATLAB will present the prompt
>>
You are now in MATLAB. From this point on, individual matlab commands may be given at
the program prompt. They will be processed when you hit the "return" key.

The MATLAB has 3-windows; MATLAB Display Windows


 Command window
(workspace)
 Graphics window: Displays
plots and graphs; Created
in response to graphics
commands.
 Editor/debugger window:
Create and edit scripts of
commands called M-files.

mat1-01-int
10
G.A. El-Sheikh MATLAB: Introductory Course 11

Online Help
Online help is available from the MATLAB prompt (a double arrow), both generally (listing
all available commands). There's even an HTML version;
>> help
[a long list of help topics follows]
In addition, for specific commands:
>> help demo
[a help message on MATLAB's demo program follows].

Type one of following commands in the command window:


 Help; lists all the help topic
 help topic; provides help for the specified topic
 help command; provides help for the specified command
 help help; provides information on use of the help command
 helpwin; opens a separate help window for navigation
 lookfor keyword; Search all M-files for keyword.

1.10 Variables
Variable names:
 Must start with a letter
 May contain only letters, digits, and the underscore “_”
 Matlab is case sensitive, i.e. one & OnE are different variables.
 Matlab only recognizes the first 31 characters in a variable name.
 Assignment statement:
‒ Variable = number;
‒ Variable = expression;
 Example:
‒ >> A1 = 1234;
‒ >> A1 = 1234
` A1 =
1234
Note that when a semi-colon ”;” is placed at the end of each command, the result is not
displayed (suppress the display).

MATLAB has built-in variables like pi, eps, and ans. You can learn their values from the
MATLAB interpreter.
>> eps
eps =
2.2204e-16
>> pi
ans =
3.1416

>> help pi

PI 3.1415926535897....
PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897....

In MATLAB all numerical computing occurs with limited precision, with all decimal
expansions being truncated at the sixteenth place. The machine's round-off, the smallest
distinguishable difference between two numbers as represented in MATLAB, is denoted by

mat1-01-int
11
G.A. El-Sheikh MATLAB: Introductory Course 12

"eps". The variable ans will keep track of the last output which was not assigned to another
variable.

 Special variables:
‒ ans: default variable name for the result
‒ pi: = 3.1415926…………
‒ eps: = 2.2204e-016, smallest amount by which 2 numbers can differ.
‒ Inf or inf: , infinity
‒ NaN or nan: not-a-number

 Commands involving variables:


‒ clc: clears the command window
‒ who: lists the names of defined variables
‒ whos: lists the names and sizes of defined variables
‒ clear: clears all variables, reset the default values of special variables.
‒ clear name: clears the variable name
‒ clf: clears the current figure and the graph window.
‒ close all: clears all current figures in the graph window.

Variable Assignment
The equality sign is used to assign values to variables:
>> x = 3

x = 3

>> y = x^2

y = 9
Variables in MATLAB are case sensitive; Hence the variables "x" and "y" are distinct from
"X" and "Y".
Output can be suppressed by appending a "semicolon" to the end of command lines,
>> x = 3;
>> y = x^2;
>> y

y =
9

Like the C/C++ and Fortran programming languages, MATLAB variables must have a value
(numerical, string of characters, logical).

Complex numbers are automatically available {by default, both i and j are initially aliased to
sqrt(-1) };
>> x = 3 + 5i
 x=
3.0000 + 5.0000i

Active Variables
At any time you want to know the active variables you can use who:

mat1-01-int
12
G.A. El-Sheikh MATLAB: Introductory Course 13

>> who
Your variables are:

ans x y
>> help who

Removing a Variable
To remove a variable, try this:
>> clear x

Saving and Restoring Variables


To save the value of the variable "x" to a plain text file named "x.value" use
>> save x.value x -ascii
To save all variables in a file named mysession.mat, in reloadable format, use
>> save mysession
To restore the session, use
>> load mysession

Variable Arithmetic
MATLAB uses some fairly standard notation. More than one command may be entered on a
single line, if they are separated by commas.
>> 2+3;
>> 3*4, 4^2;
Powers are performed before division and multiplication, which are done before subtraction
and addition.
For example
>> 2+3*4^2;
generates ans = 50. That is:
2+3*4^2 ==> 2 + 3*4^2 <== exponent has the highest precedence
==> 2 + 3*16 <== then multiplication operator
==> 2 + 48 <== then addition operator
==> 50

Double Precision Arithmetic


All arithmetic is done to double precision, which for 32-bit machines means to about 16
decimal digits of accuracy. Normally the results will be displayed in a shorter form.
>> a = sqrt(2)
a =

1.4142
>> format long, b=sqrt(2)
b =

1.41421356237310
>> format short

mat1-01-int
13
G.A. El-Sheikh MATLAB: Introductory Course 14

Command-Line Editing
The arrow keys allow "command-line editing," which cuts down on the amount of typing
required, and allows easy error correction. Press the "up" arrow, and add "/2." What will this
produce?
>> 2+3*4^2/2
Parentheses may be used to group terms, or to make them more readable. For example:
>> (2 + 3*4^2)/2
generates ans = 25.

1.11 Miscellaneous Features and Programming Issues


You may have discovered by now that MATLAB is case sensitive, that is
"a" is not the same as "A."
If this proves to be an annoyance, the command
>> casesen
will toggle the case sensitivity off and on.

The MATLAB display only shows 5 digits in the default mode. The fact is that MATLAB
always keeps and computes in a double precision 16 decimal places and rounds the display to
4 digits. The command,
>> format long % switch to display all 16 digits
>> format short % return to the shorter display.
It is possible to toggle back and forth in the scientific notation display with the commands,
>> format short e
>> format long e

>> help format  all options for this command

It is not always necessary for MATLAB to display the results of a command to the screen. If
you do not want the matrix A displayed, put a semicolon after it, A;.

Sometimes you will have spent much time creating matrices in a MATLAB session and you
would like to use these same matrices in next sessions. You can save these values in a file by
typing
>> save filename
This creates a file (filename.mat) which contains the values of the variables from your
session\workspace.

If you do not want to save all variables there are two options:
One is to clear the variables off with the command,
>> clear a b c which will remove the variables a,b,c.
The other option is to use the command,
>> save x y z which will save the variables x,y,z in the file filename.mat.

The variables can be reloaded in a future session by typing,


>> load filename

When you are ready to print out the results of a session, you can store the results in a file and
print the file from the operating system using the "print" command appropriate for your
operating system. The file is created using the command,

mat1-01-int
14
G.A. El-Sheikh MATLAB: Introductory Course 15

>> diary filename


Once a file name has been established you can toggle the diary with the commands
>> diary on
and
>> diary off
This will copy anything which goes to the screen (other than graphics) to the specified file.
Since this is an ordinary ASCII file, you can edit it later. Discussion of print out for graphics
is deferred to the project "Graphics" where MATLAB's graphics commands are presented.

MATLAB has a feature which allows you to do some of these tasks directly from MATLAB.
Let us suppose that you would like to edit a file named myfile.m and that your editor executes
on the command ed. The MATLAB command
!ed myfile.m
will bring up your editor and you can now work in it as you usually would. Obviously the
exclamation point is the critical feature here. When you are done editing, exit your editor as
you usually would, and you will find that you are back in your MATLAB session. You can
use the ! with many operating system commands.

Programming Suggestions
Here are a few pointers for programming in MATLAB:
 Try to use the indented style that makes the programs easier to read, the program syntax is
easier to check, and it forces you to think in terms of building your programs in blocks.
 Put appropriate comments in your program to tell the reader in plain English what is going
on. Some day that reader will be you, and you will wonder what you did.
 Put error messages in your programs as it will help you debug future programs.
 Always structure your output as if it will be the input of another function. For example, if
your program has "yes-no" type output, do not have it return the words "yes" and "no,"
rather return 1 or 0, so that it can be used as a condition for a branch or while loop
construction in the future.
 Try to avoid loops in your programs. MATLAB is optimized to run the built-in functions.
For a comparison, see how much faster A*B is over mult(A,B). You will be amazed at
how much economy can be achieved with MATLAB functions.
 If you are having trouble writing a program, get a small part of it running and try to build
on that. Write the program first with loops, if necessary, then go back and improve it.

Built-In Mathematical Functions


MATLAB has a platter of builtin functions for mathematical and scientific computations.
Here is a summary of relevant functions, followed by some examples:
Function Meaning Example
====================================================
sin sine sin(pi) = 0.0
cos cosine cos(pi) = 1.0
tan tangent tan(pi/4) = 1.0
asin arcsine asin(pi/2)= 1.0
acos arccosine acos(pi/2)= 0.0
atan arctangent atan(pi/4)= 1.0
exp exponential exp(1.0) = 2.7183
log natural logarithm log(2.7183) = 1.0
log10 logarithm base 10 log10(100.0) = 2.0
====================================================
The arguments to trigonometric functions are given in radians.

mat1-01-int
15
G.A. El-Sheikh MATLAB: Introductory Course 16

Example-1.1:
Let's verify that
sin(x)^2 + cos(x)^2 = 1.0
for arbitrary x. The MATLAB code is:
>> format compact % The "format compact" command eliminates spaces
between the lines of output.
>> x = pi/3;
>> sin(x)^2 + cos(x)^2 - 1.0
ans =
0

1.12 Controlling Command Window Input and Output


So far, you have been using the MATLAB command line, typing commands and expressions,
and seeing the results printed in the Command Window. This section describes how to:
 Control the appearance of the output values
 Suppress output from MATLAB commands
 Enter long commands at the command line
 Edit the command line

1.12.1 The Format Command


The format command controls the numeric format of the values displayed by MATLAB. The
command affects only how numbers are displayed, not how MATLAB computes or saves
them. Here are the different formats, together with the resulting output produced from a
vector x with components of different magnitudes.

>> x = [4/3 1.2345e-6]

>> format short


1.3333 0.0000
>> format short e
1.3333e+000 1.2345e-006
>> format short g
1.3333 1.2345e-006
>> format long
1.33333333333333 0.00000123450000
>> format long e
1.333333333333333e+000 1.234500000000000e-006
>> format long g
1.33333333333333 1.2345e-006
>> format bank
1.33 0.00
>> format rat
4/3 1/810045
>> format hex
3ff5555555555555 3eb4b6231abfd271

If the largest element of a matrix is larger than 103 or smaller than 10-3, MATLAB applies a
common scale factor for the short and long formats. In addition to the format commands
shown above

mat1-01-int
16
G.A. El-Sheikh MATLAB: Introductory Course 17

>> format compact


suppresses many of the blank lines that appear in the output. This lets you view more
information on a screen or window. If you want more control over the output format, use the
sprintf and fprintf functions.

1.12.2 Suppressing Output


If you simply type a statement and press Return or Enter, MATLAB automatically displays
the results on screen. However, if you end the line with a semicolon, MATLAB performs the
computation but does not display any output. This is particularly useful when you generate
large matrices. For example,
A = magic(100);

1.12.3 Entering Long Command Lines


If a statement does not fit on one line, use three periods, ..., followed by Return or Enter to
indicate that the statement continues on the next line. For example,
s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Blank spaces around the =, +, and - signs are optional, but they improve readability.

1.12.4 Command Line Editing


Various arrow and control keys on your keyboard allow you to recall, edit, and reuse
commands you have typed earlier. For example, suppose you mistakenly enter
rho = (1 + sqt(5))/2

You have misspelled sqrt. MATLAB responds with


Undefined function or variable 'sqt'.

Instead of retyping the entire line, simply press the key. The misspelled command is
redisplayed. Use the key to move the cursor over and insert the missing r. Repeated use of
the key recalls earlier lines. Typing a few characters and then the key finds a previous
line that begins with those characters. You can also copy previously executed commands from
the Command History. The list of available command line editing keys is different on
different computers. Experiment to see which of the following keys is available on your
machine. (Many of these keys will be familiar to users of the Emacs editor.)
Ctrl+p Recall previous line

Ctrl+n Recall next line

Ctrl+b Move back one character

Ctrl+f Move forward one character

Ctrl+ Ctrl+r Move right one word

Ctrl+ Ctrl+l Move left one word

Home Ctrl+a Move to beginning of line

End Ctrl+e Move to end of line

Esc Ctrl+u Clear line

Del Ctrl+d Delete character at cursor

mat1-01-int
17
G.A. El-Sheikh MATLAB: Introductory Course 18

Backspace Ctrl+h Delete character before cursor


Ctrl+k Delete to end of line

1.13 Programming Style and Goodness of Programs


Programming style, also known as code style, is a set of rules or guidelines used when
writing the source code for a computer program. It is often claimed that following a particular
programming style will help programmers read and understand source code conforming to the
style, and help to avoid introducing errors.

Formatting also makes information more accessible to the reader by creating and labeling
sections (headings), highlighting key words or ideas (bold, italics, or lists), and making a good
impression (professional look and feel, appropriate font choice for the document type).

You can format paragraphs in a variety of ways to improve the readability and overall
appearance and layout of a document. Using correct formatting techniques gives you much
greater control over the layout and positioning of sections, headings and paragraphs.

A classic work on the subject was The Elements of Programming Style, written in the 1970s,
and illustrated with examples from the Fortran and PL/I languages prevalent at the time. The
programming style used in a particular program may be derived from the coding
conventions of a company or other computing organization, as well as the preferences of the
author of the code. Programming styles are often designed for a specific programming
language (or language family): style considered good in C source code may not be appropriate
for BASIC source code, etc. However, some rules are commonly applied to many languages.

1.13.1 Elements of Good Style


Good style is a subjective matter, and is difficult to define. However, there are several
elements common to a large number of programming styles. The issues usually considered as
part of programming style include the layout of the source code, including indentation; the
use of white space around operators and keywords; the capitalization or otherwise of
keywords and variable names; the style and spelling of user-defined identifiers, such as
function, procedure and variable names; and the use and style of comments.

Code Appearance
Programming styles commonly deal with the visual appearance of source code, with the goal
of readability. Software has long been available that formats source code automatically,
leaving coders to concentrate on naming, logic, and higher techniques. As a practical point,
using a computer to format source code saves time, and it is possible to then enforce
company-wide standards without debates.

Indentation
Indentation styles assist in identifying control flow and blocks of code. In some programming
languages, indentation is used to delimit logical blocks of code; correct indentation in these
cases is more than a matter of style. In other languages, indentation and white space do not
affect function, although logical and consistent indentation makes code more readable.

mat1-01-int
18
G.A. El-Sheikh MATLAB: Introductory Course 19

1.13.2 Good Programming Style


 Write Clearly; don't be too clever, don't sacrifice clarity for efficiency.
 Say what you mean, simply and directly.
 Be sparing with temporary variables.
 Parenthesize to avoid ambiguity.
 Use library functions.
 Replace repetitive expressions by calls to a common function.
 Choose variable names that won't be confused.
 If a logical expression is hard to understand, try transforming it.
 Choose a data representation which makes the program simple.
 Don't patch bad code - rewrite it.
 Write and test a big program in small pieces.
 Test input for plausibility and validity.
 Identify bad input - recover if possible.
 Make sure input doesn't violate the limits of the program.
 Terminate input by end-of-file or marker, not by count.
 Make input easy to prepare and output self-explanatory.
 Make sure all variables are initialized before use.
 Watch out for off-by-one errors.
 Make sure your program "does nothing" gracefully.
 Test programs at their boundary values.
 Check some answers by hand.
 10.0 times 0.1 is hardly ever 1.0.
 Don't compare floating point numbers solely for equality.
 Make it right before you make it faster.
 Make it fail-safe before you make it faster.
 Make it clear before you make it faster.
 To make it faster, change the algorithm not small details in the code.
 Actually test code to see how fast it is.
 Make sure comments and code agree.
 Use variable names that mean something.
 Format a program to help the reader understand it.
 Don't just echo code in comments - make every comment meaningful.
 Document your data structures.
 Don't over comment.
 Don't comment bad code; rewrite it.
 Use recursive procedures for recursively defined data structures.
 Use data arrays to avoid repetitive control sequences.

mat1-01-int
19
G.A. El-Sheikh MATLAB: Introductory Course 20

1.13.3 Tips for Improving the Readability of your Code


When coding in an agile environment, making your code readable for others is key. Making
your code easier to read will also help you debug your own programs, making it easier on
yourself. Code readability is a universal subject in the world of computer programming. It's
one of the first things we learn as developers. This section presents the most important best
practices when writing readable code;
1) Commenting and Documentation
2) Consistent Indentation
3) Avoid Obvious Comments
4) Code Grouping
5) Consistent Naming Scheme
6) DRY Principle
7) Avoid Deep Nesting
8) Limit Line Length
9) File and Folder Organization
10) Consistent Temporary Names

1- Commenting and Documentation


IDEs (Integrated Development Environments) have come a long way in the past few years.
They've made commenting your code easier than ever. Following certain standards in your
comments allows IDEs and other tools to utilize them in different ways.

2- Consistent Indentation
It is a good idea to keep your indentation style consistent within your program.

The indentation style is only a matter of preference and there is no "best" style that everyone
should be following. Actually, the best style is a consistent style. If you are part of a team or if
you are contributing code to a project, you should follow the existing style that is being used
in that project.

The indentation styles are not always completely distinct from one another; sometimes they
mix different rules.

Using spaces instead of tabs for indentations is the programmer decision according to his
attitude or the work-team.

3- Avoid Obvious Comments


Commenting your code is fantastic; however, it can be overdone or just be plain redundant.
When the text is that obvious, it is really not productive to repeat it within comments.
If you must comment on that code, you can simply combine it into a single line instead.

4- Code Grouping
More often than not, certain tasks require a few lines of code. It is a good idea to keep these
tasks within separate blocks of code, with some spaces between them. Adding a comment at
the beginning of each block of code also emphasize the visual separation.

5- Consistent Naming Scheme


First of all, the names should have word boundaries. There are two popular options:
 camelCase: First letter of each word is capitalized, except the first word.
 underscores: Underscores between words, like: mysql_real_escape_string().

mat1-01-int
20
G.A. El-Sheikh MATLAB: Introductory Course 21

Having different options creates a situation similar to the indent styles, as mentioned earlier.
If an existing project follows a certain convention, you should go with that. Also, some
language platforms tend to use a certain naming scheme.

6- DRY Principle
DRY stands for Don't Repeat Yourself. Also known as DIE: Duplication is Evil.

The principle states: Every piece of knowledge must have a single, unambiguous,
authoritative representation within a system.

The purpose for most applications (or computers in general) is to automate repetitive tasks.
This principle should be maintained in all code, even web applications. The same piece of
code should not be repeated over and over again.
For example, most web applications consist of many pages. It's highly likely that these pages
will contain common elements. Headers and footers are usually best candidates for this. It's
not a good idea to keep copy-pasting these headers and footers into every page.

7- Avoid Deep Nesting


Too many levels of nesting can make code harder to read and follow. For the sake of
readability, it is usually possible to make changes to your code to reduce the level of nesting.

8- Limit Line Length


Our eyes are more comfortable when reading tall and narrow columns of text. This is
precisely the reason why newspaper articles look like this. It is a good practice to avoid
writing horizontally long lines of code. Also, if anyone intends to read the code from a
terminal window, such as Vim users, it is a good idea to limit the line length to around 80
characters.

9- File and Folder Organization


Technically, you could write an entire application's code within a single file. But that would
prove to be a nightmare to read and maintain. One of the best approaches is to either use a
framework or imitate their folder structure.

10- Consistent Temporary Names


Normally, the variables should be descriptive and contain one or more words. But, this doesn't
necessarily apply to temporary variables. They can be as short as a single character. It is a
good practice to use consistent names for your temporary variables that have the same kind of
role.

1.14 Miscellaneous MATLAB Features


You may have discovered by now that MATLAB is case sensitive, that is
"a" is not the same as "A."
If this proves to be an annoyance, the command
casesen
will toggle the case sensitivity off and on.

The MATLAB display only shows 5 digits in the default mode. The fact is that MATLAB
always keeps and computes in a double precision 16 decimal places and rounds the display to
4 digits. The command
format long

mat1-01-int
21
G.A. El-Sheikh MATLAB: Introductory Course 22

will switch to display all 16 digits and


format short
will return to the shorter display. It is also possible to toggle back and forth in the scientific
notation display with the commands
format short e
and
format long e

It is not always necessary for MATLAB to display the results of a command to the screen. If
you do not want the matrix A displayed, put a semicolon after it, A;. When MATLAB is
ready to proceed, the prompt >> will appear. Try this on a matrix right now.

Sometimes you will have spent much time creating matrices in the course of your MATLAB
session and you would like to use these same matrices in your next session. You can save
these values in a file by typing
save filename
This creates a file
filename.mat
which contains the values of the variables from your session. If you do not want to save all
variables there are two options. One is to clear the variables off with the command
clear a b c
which will remove the variables a,b,c. The other option is to use the command
save x y z
which will save the variables x,y,z in the file filename.mat. The variables can be reloaded in
a future session by typing
load filename

When you are ready to print out the results of a session, you can store the results in a file and
print the file from the operating system using the "print" command appropriate for your
operating system. The file is created using the command
diary filename
Once a file name has been established you can toggle the diary with the commands
diary on
and
diary off

This will copy anything which goes to the screen (other than graphics) to the specified file.
Since this is an ordinary ASCII file, you can edit it later. Discussion of print out for graphics
is deferred to the project "Graphics" where MATLAB's graphics commands are presented.

Some of you may be fortunate enough to be using a Macintosh or a Sun computer with a
window system that allows you to quickly move in and out of MATLAB for editing, printing,
or other processes at the system level. For those of you who are not so fortunate, MATLAB
has a feature which allows you to do some of these tasks directly from MATLAB. Let us
suppose that you would like to edit a file named myfile.m and that your editor executes on the
command ed. The MATLAB command
!ed myfile.m
will bring up your editor and you can now work in it as you usually would. Obviously the
exclamation point is the critical feature here. When you are done editing, exit your editor as

mat1-01-int
22
G.A. El-Sheikh MATLAB: Introductory Course 23

you usually would, and you will find that you are back in your MATLAB session. You can
use the ! with many operating system commands.

Variables
The variable ans will keep track of the last output which was not assigned to another
variable;
magic(6)
ans

x = ans
x = [x, eye(6)]
x

Since you have created a new variable, x, it should appear as an active variable.

To remove a variable, try this:


clear x
x (yields an error: undefined variable)
who

Variable Arithmetic
MATLAB uses some fairly standard notation. More than one command may be entered on a
single line, if they are seperated by commas.
>> 2+3;
>> 3*4, 4^2;
Powers are performed before division and multiplication, which are done before subtraction
and addition.
For example
>> 2+3*4^2;
generates ans = 50. That is:
2+3*4^2 ==> 2 + 3*4^2 <== exponent has the highest precedence
==> 2 + 3*16 <== then multiplication operator
==> 2 + 48 <== then addition operator
==> 50
Double Precision Arithmetic: All arithmetic is done to double precision, which for 32-bit
machines means to about 16 decimal digits of accuracy. Normally the results will be
displayed in a shorter form.
>> a = sqrt(2)
a=
1.4142
>> format long, b=sqrt(2)
b=
1.41421356237310
>> format short

Command-Line Editing
The arrow keys allow "command-line editing," which cuts down on the amount of typing
required, and allows easy error correction. Press the "up" arrow, and add "/2." What will this
produce?
>> 2+3*4^2/2

mat1-01-int
23
G.A. El-Sheikh MATLAB: Introductory Course 24

Parentheses may be used to group terms, or to make them more readable.


For example:
>> (2 + 3*4^2)/2
generates ans = 25.

MATLAB Demonstrations
MATLAB is shipped with a number of demonstration programs. Use help demos to find out
more about these (the number of demos will depend upon the version of Matlab you have).
Some of the standard demos may be especially useful to users who are beginners in linear
algebra:
 demo - Demonstrate some of MATLAB's capabilities
 matdemo - Introduction to matrix computation in MATLAB
 rrefmovie - Computation of Reduced Row Echelon Form

1.15 Data Types


There are 14 fundamental data types (or classes) in MATLAB. Each of these data types is in
the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-
dimensional array of any size. Two-dimensional versions of these arrays are called matrices.
All of the fundamental data types are shown in lowercase text in the diagram below. An
additional, user-defined data type, shown below as user class, is a subset of the structure
type.

The char data type


holds characters in
Unicode representation.
A character string is
merely a 1-by-n array
of characters. You can
use char to hold an
array of strings as long
as each string in the
array has the same
length. This is because MATLAB arrays must be rectangular. To hold an array of strings of
unequal length, use a cell array.

Numeric data types include signed and unsigned integers, single- and double- precision
floating point, and sparse matrices of double-precision. The following hold true for numeric
data types in MATLAB:
 All MATLAB computations are done in double-precision.
 Integer and single precision arrays offer more memory efficient storage than double-
precision.
 All data types support basic array operations, such as subscripting and reshaping.
 To perform mathematical operations on integer or single precision arrays, you must
convert them to double precision using the double function.

A cell array provides a storage mechanism for dissimilar kinds of data. You can store arrays
of different types and/or sizes within the cells of a cell array. For example, you can store a 1-
by-50 char array, a 7-by-13 double array, and a 1-by-1 uint32 in cells of the same cell

mat1-01-int
24
G.A. El-Sheikh MATLAB: Introductory Course 25

array. You access data in a cell array using the same matrix indexing used on other
MATLAB matrices and arrays.

The MATLAB structure data type is similar to the cell array in that it also stores dissimilar
kinds of data. But, in this case, it stores the data in named fields rather than in cells. This
enables you to attach a name to the groups of data stored within the structure. You access data
in a structure using these same field names.

MATLAB data types are implemented as classes. You can also create MATLAB classes of
your own. These user-defined classes inherit from the MATLAB structure class and are
shown in the previous diagram as a subset of structure.

MATLAB provides an interface to the Java programming language that enables you to create
objects from Java classes and call Java methods on these objects. A Java class is a MATLAB
data type. There are built-in and third-party classes that are already available through the
MATLAB interface. You can also create your own Java class definitions and bring them into
MATLAB.

A function handle holds information to be used in referencing a function. When you create a
function handle, MATLAB captures all the information about the function that it needs to
locate and execute, or evaluate, it later on. Typically, a function handle is passed in an
argument list to other functions. It is then used in conjunction with feval to evaluate the
function to which the handle belongs.

The following table describes the data types in some details;


Data Type Example Description
single 3*10^38 Single-precision numeric array. Single precision
requires less storage than double precision, but has less
precision and a smaller range. This data type cannot be
used in mathematical operations.
double 3*10^300 Double-precision numeric array. This is the most
5+6i common MATLAB variable type.
sparse speye(5) Sparse double-precision matrix (2-D only). The sparse
matrix stores matrices with only a few nonzero
elements in a fraction of the space required for an
equivalent full matrix. Sparse matrices invoke special
methods especially tailored to solve sparse problems.
int8, uint8, uint8(magic(3)) Signed and unsigned integer arrays that are 8, 16, and
int16, uint16,
32 bits in length. Enables you to manipulate integer
int32, uint32
quantities in a memory efficient manner. These data
types cannot be used in mathematical operations.
char 'Hello' Character array (each character is 16 bits long). This
array is also referred to as a string.
cell {17 'hello' Cell array. Elements of cell arrays contain other arrays.
eye(2)} Cell arrays collect related data and information of a
dissimilar size together.

mat1-01-int
25
G.A. El-Sheikh MATLAB: Introductory Course 26

structure a.day = 12; Structure array. Structure arrays have field names. The
a.color = 'Red'; fields contain other arrays. Like cell arrays, structures
a.mat =
magic(3); collect related data and information together.
user class inline('sin(x)') MATLAB class. This user-defined class is created
using MATLAB functions.
java class java.awt.Frame Java class. You can use classes already defined in the
Java API or by a third party, or create your own classes
in the Java language.
function @humps Handle to a MATLAB function. A function handle can
handle be passed in an argument list and evaluated using
feval.

1.16 Operator Precedence


You can build expressions that use any combination of arithmetic, relational, and logical
operators. Precedence levels determine the order in which MATLAB evaluates an expression.
Within each precedence level, operators have equal precedence and are evaluated from left to
right. The precedence rules for MATLAB operators are shown in this list, ordered from
highest precedence level to lowest precedence level:
1. Parentheses ()
2. Transpose(.'), power(.^), complex conjugate transpose('), matrix power(^)
3. Unary plus (+), unary minus (-), logical negation (~)
4. Multiplication (.*), right division (./), left division(.\), matrix multiplication (*),
matrix right division (/), matrix left division (\)
5. Addition (+), subtraction (-)
6. Colon operator (:)
7. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=),
equal to (==), not equal to (~=)
8. Logical AND (&)
9. Logical OR (|)

Overriding Default Precedence


The default precedence can be overridden using parentheses, as shown in this example;
>> A = [3 9 5];
>> B = [2 1 5];
>> C = A./B.^2

C =
0.7500 9.0000 0.2000

>> C = (A./B).^2

C =
2.2500 81.0000 1.0000
Expressions can also include values that you access through subscripts;
>> b = sqrt(A(2)) + 2*B(1)

b =
7

mat1-01-int
26
G.A. El-Sheikh MATLAB: Introductory Course 27

1.17 Exercises-01
1-Use Matlab commands to obtain the following (with displaying and suppressing the
results),
 Y1 = 123
 Y2 = 1220
 Y3 = Y1 Y2 / 50
 Y4 = Y2 / (100 Y1)

2- Assuming that x = [0:0.1:1.1] and y = [10:21]; use Matlab commands to obtain the results
for
 ‘x’ multiplied by ‘y’ and
 ‘y’ divides by ‘x’.

3- Use Matlab commands to obtain the following,


 Generate 6-by-6 magic matrix
 Generate random matrix ‘r’ of size 4 by 5
 Generate random matrix ‘r’ of size 4 by 5 with number varying between -8 and 9

4- Use Matlab commands to obtain the following,


 (3+j4) (3-j4)
 (3+j4)2
 (3+j4)3
 (3+j4)4

5- Use MATLAB commands to plot a sine and cosine graphs.

6- Use Matlab commands to obtain the following,


 sqrt(2)
 log(2)
 log10(0.23)
 cos(1.2)
 tan-1(-0.8)
 e(2+i4)
 round(1.4)
 floor(3.3)
 ceil(4.23)
 angle(4i)
 abs(2+3i)

7- Use Matlab commands to obtain the following,


 Y1  1  e  t / 
 Y2  t  e  t / 
Where =0.5, 1, 1.5

mat1-01-int
27
G.A. El-Sheikh MATLAB: Introductory Course 28

2- Vectors and Matrices


2.1 Vectors
Let's start off by creating something simple, like a vector. Enter each element of the vector
(separated by a space) between brackets, and set it equal to a variable. For example, to create
the vector a, enter into the Matlab command window:
>> a1 = [1 2 3 4 5 6 9 8 7]
Matlab should return:
a1 =
1 2 3 4 5 6 9 8 7

Let's say you want to create a vector with elements between 0 and 20 evenly spaced in
increments of 2:
>> t1 = 0:2:20

t1 =
0 2 4 6 8 10 12 14 16 18 20

 A row vector in MATLAB can be created by an explicit list, starting with a left bracket -[-,
entering the values separated by spaces (or commas) and closing the vector with a right
bracket -]-.
 A column vector can be created the same way, and the rows are separated by semicolons.
Example:
‒ >> x1 = [ 0, 0.25*pi, 0.5*pi, 0.75*pi, pi ]
x1 =
0 0.7854 1.5708 2.3562 3.1416 (x is a row vector.)
‒ >> y1 = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ]
y1 =
0
0.7854
1.5708
2.3562
3.1416 (y is a column vector.)

 Vector Addressing; A vector element is addressed in MATLAB with an integer index


enclosed in parentheses.
 Example:
‒ >> x1(3)
ans = 1.5708  3rd element of vector x1
 The colon notation may be used to address a block of elements;
‒ (start : increment : end)
‒ start is the starting index, increment is the amount to add to each successive index, and
end is the ending index.
‒ A shortened format (start : end) may be used if increment is 1.
 Example:
‒ >> x1(1:3)
ans =
0 0.7854 1.5708  1st to 3rd elements of vector x1

mat1-02-vector
28
G.A. El-Sheikh MATLAB: Introductory Course 29

 NOTE: MATLAB index starts at 1.

Some useful commands:


x = start:end create row vector x starting with start, counting by one, ending
at end
x = start : increment : end create row vector x starting with start, counting by increment,
ending at or before end
linspace(start, end, number) create row vector x starting with start, ending at end, having
number elements
length(x) returns the length of vector x
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.

Manipulating vectors is almost as easy as creating them. First, suppose you would like to add
2 to each of the elements in vector 'a'. The equation for that looks like:
>> b1 = a1 + 2

b1 =
3 4 5 6 7 8 11 10 9

Now suppose, you would like to add two vectors together; if the two vectors are the same
length, it is easy. Simply add the two as follows:
>> c1 = a1 + b1

c1 =
4 6 8 10 12 14 20 18 16

Subtraction of vectors of the same length works exactly the same way.

2.2 Matrices
A Matrix array is two-dimensional, having both multiple rows and multiple columns, similar
to vector arrays:
‒ it begins with [, and end with ]
‒ spaces or commas are used to separate elements in a row
‒ semicolon or enter is used to separate rows.

A matrix is a rectangular array (matrix m-by-n) of numbers;


a 11 a 12 a 13 .... a 1n 
a 
 21 a 22 a 23 .... a 2 n 
A  a 31 a 32 a 33 .... a 3n 
 
     
a m1 a m 2 a m 3 .... a mn 
The main diagonal is a vector;
diag (A)  a 11 a 22 a 33 ..... a mn 

mat1-02-vector
29
G.A. El-Sheikh MATLAB: Introductory Course 30

Entering matrices into Matlab is the same as entering a vector, except each row of elements is
separated by a semicolon (;) or a return:

>> B1 = [1 2 3 4;5 6 7 8;9 10 11 12]

B1 =
1 2 3 4
5 6 7 8
9 10 11 12
Or
>> B1 = [ 1 2 3 4
5 6 7 8
9 10 11 12]

B1 =
1 2 3 4
5 6 7 8
9 10 11 12

Example-2.1: The matrix


1 4 7 9
8 7 3 6
 
6 5 3 2
defines a matrix with 3 rows, 4 columns, and 12 elements;
>> [1 4 7 9; 8 7 3 6; 6 5 3 2];

MATLAB works with essentially only one kind of object, a rectangular numerical matrix
possibly, with complex entries. Every MATLAB variable refers to a matrix [a number is a 1
by 1 matrix]. In some situations, 1-by-1 matrices are interpreted as scalars, and matrices with
only one row or one column are interpreted as vectors.

2.3 Built-In Matrix Functions


MATLAB has many types of matrices which are built into the system e.g.,
Function Description
diag returns diagonal M.E. as vector
eye identity matrix
hilb Hilbert matrix
magic magic square
ones matrix of ones
rand randomly generated matrix
triu upper triangular part of a matrix
tril lower triangular part of a matrix
zeros matrix of zeros

2.3.1 Matrices of Random Entries


A 3 by 3 matrix with random entries is produced by typing
>> rand(3)
ans =
0.0470 0.9347 0.8310
0.6789 0.3835 0.0346
0.6793 0.5194 0.0535

mat1-02-vector
30
G.A. El-Sheikh MATLAB: Introductory Course 31

>>
General m by n matrices of random entries are generated with
>> rand(m,n);

2.3.2 Magic Squares


A magic square is a square matrix which has equal sums along all its rows and columns. For
example:
>> magic(4)
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>>
The elements of each row and column sum to 34.

>> m1=magic(4)
m1 =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> sum(m1)
ans =
34 34 34 34
>> sum(m1')
ans =
34 34 34 34

2.3.3 Matrices of Ones


The functions;
eye (m,n) produces an m-by-n matrix of ones.
eye (n) produces an n-by-n matrix of ones.

2.3.4 Matrices of Zeros


The commands;
zeros (m,n) produces an m-by-n matrix of zeros.
zeros (n) produces an n-by-n one;
If A is a matrix, then zeros(A) produces a matrix of zeros of the same size as A.

2.3.5 Diagonal Matrices


If x is a vector, diag(x) is the diagonal matrix with x down the diagonal.
>> a1=[1 2 3 4];
>> diag(a1)

ans =
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4

mat1-02-vector
31
G.A. El-Sheikh MATLAB: Introductory Course 32

If A is a square matrix, then diag(A) is a vector consisting of the diagonal of A.


>> b1=[a1.^2;a1;a1.^2;a1]

b1 =
1 4 9 16
1 2 3 4
1 4 9 16
1 2 3 4

>> diag(b1)

ans =
1
2
9
4

What is diag(diag(A))?
>> diag(diag(b1))

ans =
1 0 0 0
0 2 0 0
0 0 9 0
0 0 0 4

>> diag(diag(a1))

ans =
1
2
3
4

2.4 Defining Matrices in MATLAB


MATLAB is designed to make definition of matrices and matrix manipulation as simple as
possible. Matrices can be introduced into MATLAB in several different ways:
 Entered by an explicit list of elements,
 Generated by built-in statements and functions,
 Created in M-files (see section below),
 Loaded from external data files (see details below).

For example, either of the statements


>> A = [1 2 3; 4 5 6; 7 8 9];
and
>> A = [ 1 2 3
4 5 6
7 8 9 ]
creates the obvious 3-by-3 matrix and assigns it to a variable A.

mat1-02-vector
32
G.A. El-Sheikh MATLAB: Introductory Course 33

Note that:
 The elements within a row of a matrix may be separated by commas as well as a blank.
 The elements of a matrix being entered are enclosed by brackets;
 A matrix is entered in "row-major order" [i.e. all of the first row, then all of the second
row, etc];
 Rows are separated by a semicolon [or a newline], and the elements of the row may be
separated by either a comma or a space. [Caution: Watch out for extra spaces!]

When listing a number in exponential form (e.g. 2.34e-9), blank spaces must be avoided.
Listing entries of a large matrix is best done in an M-file (see section below), where errors can
be easily edited away.
The matrix element located in the i'th row and j'th column of a is referred to in the usual way:
>> A(1,2), A(2,3)
ans =
2
ans =
6
>>
It's very easy to modify matrices:
>> A(2,3) = 10;
>> A
A =
1 2 3
4 5 10
7 8 9

Building Matrices
Matlab has many types of matrices which are built into the system. For example, a 7 by 7
matrix with random entries is produced by typing
>> rand(7)

You can generate random matrices of other sizes and get help on the rand command within
matlab:
>> rand(2,5)
>> help rand

Another special matrix, called a Hilbert matrix, is a standard example in numerical linear
algebra.
>> hilb(5)
>> help hilb

A 5 by 5 magic square is given by the next command:


>> magic(5)
>> help magic

A magic square is a square matrix which has equal sums along all its rows and columns. This
matrix can be used in multiplication to check this property.
Some of the standard matrices from linear algebra are easily produced as follows:
>> eye(6)
>> zeros(4,7)
>> ones(5)

mat1-02-vector
33
G.A. El-Sheikh MATLAB: Introductory Course 34

You can also build matrices of your own with any entries that you may want such as;
>> [1 2 3 5 7 9]
>> [1, 2, 3; 4, 5, 6; 7, 8, 9]
>> [1 2 RET 3 4 RET 5 6]
Note that if you are using cut-and-paste features of a window system or editor to copy these
examples into Matlab then you should not use cut-and-paste and the last line above. Type it in
by hand, touching the Return or Enter key where you see RET, and check to see whether the
carriage returns make any difference in Matlab's output.

Matlab syntax is convenient for blocked matrices as follows:


>> [eye(2); zeros(2)]
>> [eye(2); zeros(3)]
>> [eye(2), ones(2,3)]
Did any of these three examples produce error messages? What is the problem?

2.5 Engineering Application of Matrices


In the analysis of a wide range of engineering applications, matrices are a convenient means
of representing transformations between coordinate systems, and for writing (moderate to
large) families of equations representing the state of a system (e.g., equations of equilibrium,
energy and momentum conservation, and so forth).

Example-2.2:
Suppose that the following three equations describe the equilibrium of a simple structural
system as a function of external loads and computed displacements;
3 x1  x 2  1
 x1  4 x 2  2 x 3  5
 2 x 2  10 x 3  26
These equations can be rewritten as
3 x 1  x 2  (0) x 3  1
 x1  4 x 2  2 x 3  5
(0) x 1  2 x 2  10 x 3  26

This family of equations can be written in the form ( A X  B ), where


 x1   3 1 0  1
  
X   x 2  , A   1 6  2 , B   5 

 x 3   0  2 10  26

In a typical application, matrices A and B will be defined by the parameters of the


engineering problem, and the solution matrix X will need to be computed.

Depending on the specific values of coefficients in matrices A and B, there may be:
(a) no solutions to A X  B ,
(b) a unique solution to A X  B , or
(c) an infinite number of solutions to A.X = B.
In this particular case, however, the solution matrix;

mat1-02-vector
34
G.A. El-Sheikh MATLAB: Introductory Course 35

1 
X  2
3
This solution makes the right-hand side of the matrix equations (i.e. A.X) equals the left-hand
side of the matrix equations (i.e. matrix B). The family of matrix equations can be setup and
solved easily in MATLAB as discussed in next sections and later in this course.

2.6 Subscripting and Indexing


This section explains how to use subscripting to access and assign to elements of a MATLAB
matrix.

2.6.1 Accessing Single Elements of a Matrix


The element in row i and column j of A is denoted by A(i,j). For example, suppose A =
magic(4), Then A(4,2) is the number in the fourth row and second column. For our magic
square, A(4,2) is 14.
>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

>> A(4,2)
ans =
14
It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the
usual way of referencing row and column vectors. But it can also apply to a fully two-
dimensional matrix, in which case the array is regarded as one long column vector formed
from the columns of the original matrix. So, for our magic square, A(8) is another way of
referring to the value 14 stored in A(4,2).
>> A(8)
ans =
14

2.6.2 Accessing Multiple Elements of a Matrix


It is possible to compute the sum of the elements in the fourth column of A by typing
>> A(1,4) + A(2,4) + A(3,4) + A(4,4)
You can reduce the size of this expression using the colon operator. Subscript expressions
involving colons refer to portions of a matrix.
>> A(1:m,n)
refers to the elements in rows 1 through m of column n of the A matrix. Using this notation,
you can compute the sum of the fourth column of A more succinctly.
>> sum(A(1:4,4))
The colon by itself refers to all the elements in a row or column of a matrix. The keyword end
refers to the last row or column. Using the following syntax, you can compute this same
column sum without having to specify row and column numbers.
>> sum(A(:,end))

mat1-02-vector
35
G.A. El-Sheikh MATLAB: Introductory Course 36

ans =
34
By adding an additional colon operator, you can refer to nonconsecutive elements in a matrix.
The m:3:n in this expression means to make the assignment to every third element in the
matrix.
>> B = A;
>> B(1:3:end) = -10
B =
-10 2 3 -10
5 11 -10 8
9 -10 6 12
-10 14 15 -10
You can repeatedly access an array element using the ones function. To create a new 2-by-6
matrix out of the 9th element of A,
>> B = A(9*ones(2,6))
B =
3 3 3 3 3 3
3 3 3 3 3 3

2.6.3 Expanding the Size of a Matrix


If you try to access an element outside of the matrix, it is an error
>> B = A(4,5)
Index exceeds matrix dimensions
However, if you store a value in an element outside of the matrix, the size of the matrix
increases to accommodate the new element.
>> B = A;
>> B(4,5) = 17
B =
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
Similarly, you can expand a matrix by assigning to a series of matrix elements;
>> B(2:5,5:6) = 5
B =
16 2 3 13 0 0
5 11 10 8 5 5
9 7 6 12 5 5
4 14 15 1 5 5
0 0 0 0 5 5

2.6.4 Deleting Rows and Columns


You can delete rows and columns from a matrix using just a pair of square brackets. Start
with
>> X = A;
Then, to delete the second column of X, use
>> X(:,2) = []
This changes X to
X =
16 3 13
5 10 8

mat1-02-vector
36
G.A. El-Sheikh MATLAB: Introductory Course 37

9 6 12
4 15 1
If you delete a single element from a matrix, the result isn't a matrix anymore. So expressions
like
>> X(1,2) = []
result in an error. However, using a single subscript deletes a single element, or sequence of
elements, and reshapes the remaining elements into a row vector. So
>> X(2:2:10) = []
results in
X =
16 9 3 6 13 12 1

2.6.5 Concatenating Matrices


Concatenation is the process of joining small matrices together to make bigger ones. In fact,
you made your first matrix by concatenating its individual elements. The pair of square
brackets, [], is the concatenation operator. For an example, start with the 4-by-4 magic square
(A) and form;
>> A = magic(4);
>> B = [A A+32;A+48 A+16]
The result is an 8-by-8 matrix, obtained by joining the four submatrices.
B =
16 2 3 13 48 34 35 45
5 11 10 8 37 43 42 40
9 7 6 12 41 39 38 44
4 14 15 1 36 46 47 33
64 50 51 61 32 18 19 29
53 59 58 56 21 27 26 24
57 55 54 60 25 23 22 28
52 62 63 49 20 30 31 17

This matrix is half way to being another magic square. Its elements are a rearrangement of the
integers 1:64. Its column sums are the correct value for an 8-by-8 magic square.
>> sum(B)
ans =
260 260 260 260 260 260 260 260

But, its row sums, sum(B')', are not all the same. Further manipulation is necessary to make
this a valid 8-by-8 magic square.

2.6.6 Advanced Indexing


MATLAB stores each array as a column of values regardless of the actual dimensions. This
column consists of the array columns, appended end to end.
For example, MATLAB stores
>> A = [2 6 9; 4 2 8; 3 0 1]
as
2
4
3
6
2
0
9
8

mat1-02-vector
37
G.A. El-Sheikh MATLAB: Introductory Course 38

1
Accessing A with a single subscript indexes directly into the storage column;
 A(3) accesses the third value in the column, the number 3.
 A(7) accesses the seventh value, 9, and so on.

If you supply more subscripts, MATLAB calculates an index into the storage column based
on the dimensions you assigned to the array. For example, assume a two-dimensional array
like A has size [d1 d2], where d1 is the number of rows in the array and d2 is the number of
columns. If you supply two subscripts (i,j) representing row-column indices, the offset is
>> (j-1)*d1+i
Given the expression A(3,2), MATLAB calculates the offset into A's storage column as (2-
1)*3+3, or 6. Counting down six elements in the column accesses the value 0.

2.6.7 Indexing into Multidimensional Arrays


This storage and indexing scheme also extends to multidimensional arrays. In this case,
MATLAB operates on a page-by-page basis to create the storage column, again appending
elements column-wise.

For example, consider a 5-by-4-by-3-by-2 array C.

Again, a single subscript indexes directly into this column. For example, C(4) produces the
result
ans =
0
If you specify two subscripts (i,j) indicating row-column indices, MATLAB calculates the
offset as described above. Two subscripts always access the first page of a multidimensional
array, provided they are within the range of the original array dimensions. If more than one
subscript is present, all subscripts must conform to the original array dimensions. For
example, C(6,2) is invalid, because all pages of C have only five rows. If you specify more
than two subscripts, MATLAB extends its indexing scheme accordingly. For example,
consider four subscripts (i,j,k,l) into a four-dimensional array with size [d1 d2 d3 d4].
MATLAB calculates the offset into the storage column by
(l-1)(d3)(d2)(d1)+(k-1)(d2)(d1)+(j-1)(d1)+i

For example, if you index the array C using subscripts (3,4,2,1), MATLAB returns the value 5
(index 38 in the storage column).
In general, the offset formula for an array with dimensions [d1 d2 d3 ... dn] using any
subscripts (s1 s2 s3 ... sn) is
(sn-1)(dn-1)(dn-2)...(d1)+(sn-1-1)(dn-2)...(d1)+...+(s2-1)(d1)+s1

Because of this scheme, you can index an array using any number of subscripts. You can
append any number of 1s to the subscript list because these terms become zero. For example,
C(3,2,1,1,1,1,1,1)
is equivalent to
C(3,2)

2.6.8 Building Matrices from Block


Large matrices can be assembled from smaller matrix blocks. For example, with matrix A in
hand, we can enter the following commands;
>> C = [A; 10 11 12]; <== generates a (4x3) matrix

mat1-02-vector
38
G.A. El-Sheikh MATLAB: Introductory Course 39

>> [A; A; A]; <== generates a (9x3) matrix


>> [A, A, A]; <== generates a (3x9) matrix
As with variables, use of a semicolon with matrices suppresses output. This feature can be
especially useful when large matrices are being generated.
If A is a 3-by-3 matrix, then
>> B = [ A, zeros(3,2); zeros(2,3), eye(2) ];
will build a certain 5-by-5 matrix; Try it.

2.7 Matrix Operations


The following matrix operations are available in MATLAB:
Operator Description Operator Description
+ addition ' transpose

- subtraction \ left division

* multiplication / right division

^ power

These matrix operations apply, of course, to scalars (1-by-1 matrices) as well. If the sizes of
the matrices are incompatible for the matrix operation, an error message will result, except in
the case of scalar-matrix operations (for addition, subtraction, and division as well as for
multiplication) in which case each entry of the matrix is operated on by the scalar.

2.7.1 Matrix Transpose


The transpose of a matrix is the result of interchanging rows and columns. MATLAB denotes
the [conjugate] transpose by following the matrix with the single-quote [apostrophe]. The
transpose (') flips a matrix about its main diagonal and it turns a row vector into a column
vector.

Example:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9

>> A'
ans =
1 4 7
2 5 8
3 6 9
>> B = [1+i 2 + 2*i 3 - 3*i]'
B =
1.0000 - 1.0000i
2.0000 - 2.0000i
3.0000 + 3.0000i
>>

mat1-02-vector
39
G.A. El-Sheikh MATLAB: Introductory Course 40

>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]


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

>> sum(A) % (produces a row vector containing the column sums)


ans =
34 34 34 34

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

>> sum(A')' % (produces a column vector containing the row sums)


ans =
34
34
34
34

The sum of the elements on the main diagonal is easily obtained;


>> diag(A)
ans =
16
10
7
1

>> sum(diag(A))
ans =
34

There are functions intended for use in graphics, such as flip, fliplr (flips a matrix from
left to right) and flipud;
>> sum(diag(fliplr(A)))
ans =
34

2.7.2 Matrix Addition/Subtraction


Let matrix "A" have m rows and n columns, and matrix "B" have p rows and q columns. The
matrix sum "A + B" is defined only when m equals p and n = q, The result is a n by m matrix
having the element-by-element sum of components in A and B.
For example:
>> E = [ 2 3; 4 5.0; 6 7];
>> F = [ 1 -2; 3 6.5; 10 -45];
>> E+F

mat1-02-vector
40
G.A. El-Sheikh MATLAB: Introductory Course 41

ans =
3.0000 1.0000
7.0000 11.5000
16.0000 -38.0000
>>

2.7.3 Matrix Multiplication


Matrix multiplication requires that the sizes match. If they don't, an error message is
generated;
>> A=
>> B=
>> A*B, B*A;
>> B'*A;
>> A*A', A'*A;
>> B'*B, B*B';

Scalars multiply matrices as expected, and matrices may be added in the usual way (both are
done "element by element):
>> 2*A, A/4;
>> A + [b,b,b];

Example: We can use matrix multiplication to check the "magic" property of magic squares;
>> A = magic(5);
>> b = ones(5,1);
>> A*b; <== (5x1) matrix containing row sums.
>> v = ones(1,5);
>> v*A; <== (1x5) matrix containing column sums.

2.7.4 Matrix Inversion


The matrix inversion is necessary in mathematical operations especially the solution of
algebraic equations. However, due to the limitation of this course the matrix should be non-
singular square. For example,
>> A = [1 2 3; 4 5 6; 7 8 9];
>> inv(A)

Warning: Matrix is close to singular or badly scaled.


Results may be inaccurate. RCOND = 1.541976e-018.
ans =
1.0e+016 *
-0.4504 0.9007 -0.4504
0.9007 -1.8014 0.9007
-0.4504 0.9007 -0.4504

>> A = [1 2 3; 6 9 6; 7 8 10];
>> inv(A)
ans =
-1.0769 -0.1026 0.3846
0.4615 0.2821 -0.3077
0.3846 -0.1538 0.0769

Alternatively, in case of ill-conditioned matrix its pseudo-inverse can be obtained as;

mat1-02-vector
41
G.A. El-Sheikh MATLAB: Introductory Course 42

>> B2=pinv(A)

B2 =
-0.6389 -0.1667 0.3056
-0.0556 -0.0000 0.0556
0.5278 0.1667 -0.1944

2.7.5 Matrix Functions "any" and "all"


There is a function to determine if a matrix has at least one nonzero entry, any, as well as a
function to determine if all the entries are nonzero, all.
>> A = zeros(1,4)
>> any(A); True if any element of a vector is a nonzero
number or is logical 1 (TRUE). ANY ignores entries
that are NaN (Not a Number).
>> D = ones(1,4)
>> any(D)
>> all(A); True if all elements of a vector are nonzero.

2.7.6 Returning more than One Value


Some MATLAB functions can return more than one value. In the case of max the interpreter
returns the maximum value and also the column index where the maximum value occurs.
>> [m, i] = max(B)
>> min(A)
>> b = 2*ones(A)
>> A*B
>> A

2.7.7 Round Floating Point numbers to Integers


MATLAB has functions to round floating point numbers to integers. MATLAB has functions
to round floating point numbers to integers. These are round, fix, ceil, and floor. The next
few examples work through this set of commands and a couple more arithmetic operations.
>> f = [-.5 .1 .5];
>> round(f)
>> fix(f)
>> ceil(f)
>> floor(f)
>> sum(f)
>> prod(f)

2.7.8 Matrix-Element Level Operations


When they are taken away from the world of linear algebra, matrices become two dimensional
numeric arrays. Arithmetic operations on arrays are done element-by-element. This means
that addition and subtraction are the same for arrays and matrices, but that multiplicative
operations are different. MATLAB uses a dot, or decimal point, as part of the notation for
multiplicative array operations.
The matrix operations of addition and subtraction already operate on an element-by-element
basis, but the other matrix operations given above do not, they are matrix operations.

The list of operators includes:

mat1-02-vector
42
G.A. El-Sheikh MATLAB: Introductory Course 43

+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose

The dot in front of the operations forces them to perform entry-by-entry multiplication instead
of the usual matrix operation.
For example
[1,2,3,4].*[1,2,3,4]

ans =
1 4 9 16
The same result can be obtained with
[1,2,3,4].^2
Element-by-element operations are particularly useful for MATLAB graphics.

The magic square is multiplied by itself with array multiplication,


>> A.*A
The result is an array containing the squares of the integers from 1 to 16, in an unusual order;
ans =
256 9 4 169
25 100 121 64
81 36 49 144
16 225 196 1

2.7.9 Sub-Matrices
The element in row i and column j of A is denoted by A(i,j).
For example:
A(4,2) is the number in the fourth row and second column.
For our magic square, A(4,2) is 15.
So it is possible to compute the sum of the elements in the fourth column of A by typing
A(1,4) + A(2,4) + A(3,4) + A(4,4)
This produces
ans =
34

We have already seen how colon notation can be used to generate vectors. A very common
use of the colon notation is to extract rows, or columns, as a sort of "wild-card" operator
which produces a default list.
For example:
A(1:4,3)
is the column vector consisting of the first four entries of the third column of A. A colon by
itself denotes an entire row or column. So, for example:
A(:,3)
is the third column of A, and
A(1:4,:)
is the first four rows of A.

mat1-02-vector
43
G.A. El-Sheikh MATLAB: Introductory Course 44

Arbitrary integral vectors can be used as subscripts. The statement


A(:,[2 4])
contains as columns, columns 2 and 4 of matrix A. This subscripting scheme can be used on
both sides of an assignment statement:
A(:,[2 4 5]) = B(:,1:3)
replaces columns 2,4,5 of matrix A with the first three columns of matrix B. Note that the
"entire" altered matrix A is printed and assigned. Try it.

Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix [1 2;3 4]:
A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]

Once again, the entire altered matrix is printed and assigned.


When you insert a 0-1 vector into the column position then the columns which correspond to
1's are displayed.
>> V=[0 1 0 1 1]
>> A(:,V)
>> A(V,:)

MATLAB actually has a built-in function that creates magic squares of almost any size;
>> B = magic(4)
B =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

To swap the two middle columns;


>> B1 = B(:,[1 3 2 4])
Each of the rows of matrix B, and reorder the elements in the order 1, 3, 2, 4 to produce,
B1 =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

2.8 Empty Matrices


A matrix having at least one dimension equal to zero is called an empty matrix. The simplest
empty matrix is 0-by-0 in size. Examples of more complex matrices are those of dimension 0-
by-5 or 10-by-0-by-20. To create a 0-by-0 matrix, use the square bracket operators with no
value specified.
>> A = [];
>> whos A
Name Size Bytes Class

A 0x0 0 double array

You can create empty arrays of other sizes using the zeros, ones, rand, or eye functions.
To create a 0-by-5 matrix, for example, use
E = zeros(0,5)

mat1-02-vector
44
G.A. El-Sheikh MATLAB: Introductory Course 45

2.8.1 Operating on an Empty Matrix


The basic model for empty matrices is that any operation that is defined for m-by-n matrices,
and that produces a result whose dimension is some function of m and n, should still be
allowed when m or n is zero. The size of the result should be that same function, evaluated at
zero.

For example, horizontal concatenation


C = [A B]
requires that A and B have the same number of rows. So if A is m-by-n and B is m-by-p, then
C is m-by-(n+p). This is still true if m or n or p is zero.
Many operations in MATLAB produce row vectors or column vectors. It is possible for the
result to be the empty row vector
r = zeros(1,0)
or the empty column vector
C = zeros(0,1)
As with all matrices in MATLAB, you must follow the rules concerning compatible
dimensions. In the following example, an attempt to add a 1-by-3 matrix to a 0-by-3 empty
matrix results in an error.
[1 2 3] + ones(0,3)
??? Error using ==> +
Matrix dimensions must agree.
Some MATLAB functions, like sum and max, are reductions. For matrix arguments, these
functions produce vector results; for vector arguments they produce scalar results. Empty
inputs produce the following results with these functions:
 sum([ ]) is 0
 prod([ ]) is 1
 max([ ]) is [ ]
 min([ ]) is [ ]

2.8.2 Using Empty Matrices with If or While


When the expression part of an if or while statement reduces to an empty matrix,
MATLAB evaluates the expression as being false. The following example executes
statement S0, because A is an empty array.
A = ones(25,0,4);

if A
S1
else
S0
end

mat1-02-vector
45
G.A. El-Sheikh MATLAB: Introductory Course 46

2.9 Exercises-02
Use MATLAB commands to;
1) find the sum and average of one dimensional integer array.
2) swap first and last element of an integer 1-d array.
3) reverse the elements of an integer 1-D array.
4) find the largest and smallest element of an array.
5) Suppose X. Y, Z are arrays of integers of size M, N, and M + N respectively. The
numbers in array X and Y appear in descending order. Find Z by merging arrays X and
Y in descending order.
6) Generate 6-by-6 magic matrix
7) Show the results of ‘x’ multiplied by ‘y’ and ‘y’ divides by ‘x’; Given x = [0:0.1:1.1]
and y = [10:21].
8) Generate random matrix ‘r’ of size 4 by 5 with number varying between -8 and 9.
9) input elements into matrix of size m x n (e.g. 3x2); display matrix-elements; Sum of all
elements of matrix of size m x n; display row-wise sum of matrix of size m x n; display
column-wise sum of matrix of size m x n; create transpose of matrix B of size n x m and
find the inverse of that matrix.
10) find the multiplication of two-dimensional arrays (matrices) A and B.
11) Let
t = [2 3 4 5 6 7 8 9]
y1 = [1 2 3 -2 -2 4 4 4]
y2 = [2 2 2 2 1 0 -1 -2]
Use Matlab to superimpose on a single plot the elements of y1 versus the elements of t with
a solid red curve and the elements of y2 versus the elements of t with a dashed blue curve.
Use Matlab to put a legend on your plot that indicates which curve is which.

12) Use MATLAB commands to get exactly as the plots shown in Fig. 2.1.
Sinusoidal Functions
1
sin
0.8 cos

0.6

0.4 Fig. 2.1


0.2
Amplitude

-0.2

-0.4

-0.6

-0.8

-1
1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5
Angle [rad]

13) Start MATLAB and clear the workspace and verify that no current variables exist in the
workspace, then carry on the following
 Generate a row vector A whose first element is 4 and whose second element is 7.

mat1-02-vector
46
G.A. El-Sheikh MATLAB: Introductory Course 47

 Generate a column vector B from row vector A. The elements of vector B should have
the same values as those in vector A. What is the size of vector B?
 Generate a column vector C of 12 elements, each of which is 0.
 Generate a 12x12 matrix D, each of whose elements is 1.
 Replace the 30th element of D with the value 9.
 Replace the element located in the 5th row and 4th column in D with a 4.
 Replace the first column in D with C. Does the number of rows change?
 Generate a row vector E that starts at 2, ends at 40, and has an increment of 2. How
many elements are there in vector E? Do any of the elements have a value of 39?
 Generate a vector F from the last 14 elements in E. What is the value of the 3rd
element of F?
 How many elements are there in a vector that starts at 1, ends at 45, with increments
of 3?
 Make a 12x2 matrix called G from C and the 3rd column of D.
 Does any element in G equal 9? If yes, what is its location?
 Generate a 12x4 matrix H only using row vector A. What is the value of element #7?
 Generate a column vector that runs sequentially from 2 to 13 and call it I.
 Generate a row vector that runs sequentially from 13 to 2. (i.e. Increment = -1.)
 Generate a 100x100 square matrix of ones and display. Interrupt the display after a
few seconds.
 List the directory of variables currently in memory. How many total bytes are used?
How many variables have been generated?

mat1-02-vector
47
G.A. El-Sheikh MATLAB: Introductory Course 48

3- Polynomials in MATLAB
The objective of this section is to learn how to represent polynomials in MATLAB, find roots
of polynomials, create polynomials when roots are known and obtain partial fractions.

3.1 Polynomial Function Summary


MATLAB provides functions for standard polynomial operations, such as polynomial roots,
evaluation, and differentiation. In addition, there are functions for more advanced
applications, such as curve fitting and partial fraction expansion. Symbolic Math Toolbox
contains additional specialized support for polynomial operations.

Function Description
Conv Multiply polynomials
Deconv Divide polynomials
Poly Polynomial with specified roots
Polyder Polynomial derivative
Polyfit Polynomial curve fitting
Polyval Polynomial evaluation
Polyvalm Matrix polynomial evaluation
Residue Partial-fraction expansion (residues)
Roots Find polynomial roots

3.2 Representing Polynomials


MATLAB represents polynomials as row vectors containing coefficients ordered by
descending powers. For example, consider the equation,
P( x )  x 3  2 x  5
To enter this polynomial into MATLAB, use
>> p = [1 0 -2 -5];

In Matlab, a polynomial is represented by a vector. To create a polynomial in Matlab, simply


enter each coefficient of the polynomial into the vector in descending order. For instance, let's
say you have the following polynomial:

To enter this into Matlab, just enter it as a vector in the following manner

x = [1 3 -15 -2 9]

x=
1 3 -15 -2 9
Matlab can interpret a vector of length n+1 as an nth order polynomial. Thus, if your
polynomial is missing any coefficients, you must enter zeros in the appropriate place in the
vector.

For example,

would be represented in Matlab as:

y = [1 0 0 0 1]

mat1-03-poly
48
G.A. El-Sheikh MATLAB: Introductory Course 49

3.3 Polynomial Roots


The roots function calculates the roots of a polynomial:
>> r = roots(p)
r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i

By convention, MATLAB stores roots in column vectors. The function poly returns to the
polynomial coefficients:
>> p2 = poly(r)
p2 =
1 8.8818e-16 -2 -5
poly and roots are inverse functions.

You can also extract the roots of a polynomial. This is useful when you have a high-order
polynomial such as;

Finding the roots would be as easy as entering the following command;

roots([1 3 -15 -2 9])

ans =
-5.5745
2.5836
-0.7951
0.7860

3.4 Polynomial Evaluation


The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use
>> polyval(p,5)
ans =
110

It is also possible to evaluate a polynomial in a matrix sense. In this case the equation
( P( x)  x 3  2 x  5 ) becomes ( P(x)  x 3  2 x  5 I ), where X is a square matrix and I is the
identity matrix.

For example, create a square matrix X and evaluate the polynomial p at X:


>> X = [2 4 5; -1 0 3; 7 1 5];
>> Y = polyvalm(p,X)
Y=
377 179 439
111 81 136
490 253 639
You can find the value of a polynomial using the polyval function. For example, to find the
value of the above polynomial ( ) at s=2,

mat1-03-poly
49
G.A. El-Sheikh MATLAB: Introductory Course 50

>> z = polyval([1 0 0 0 1],2)

z=
17

3.5 Convolution and Deconvolution


Polynomial multiplication and division correspond to the operations convolution and
deconvolution.

Polynomial Multiplication:
Let's say you want to multiply two polynomials together. The product of two polynomials is
found by taking the convolution of their coefficients. Matlab's function conv that will do this
for you;
>> x = [1 2];
>> y = [1 4 8];
>> z = conv(x,y)

z =
1 6 16 16

The functions conv and deconv implement these operations. Consider the polynomials
( P1  s 2  2 s  3 ) and ( P2  4s 2  5 s  6 ).

To compute their product,


>> p1 = [1 2 3];
>> p2 = [4 5 6];
>> p12 = conv(p1,p2)
P12 =
4 13 28 27 18

Polynomial Division:
Use deconvolution to divide back out of the product:
>> [q,r] = deconv(p12,p1)
q=
456
r=
00000

>> [q,r] = deconv(p12,p2)


q=
1 2 3
r=
0 0 0 0 0

Dividing two polynomials is just as easy. The deconv function will return the remainder as
well as the result. Let's divide z by y and see if we get x.

[xx, R] = deconv(z,y)

mat1-03-poly
50
G.A. El-Sheikh MATLAB: Introductory Course 51

xx =
1 2

R =
0 0 0 0
As you can see, this is just the polynomial/vector x from before. If y had not gone into z
evenly, the remainder vector would have been something other than zero.

Polynomial Addition:
If you want to add two polynomials together which have the same order, a simple z=x+y will
work (the vectors x and y must have the same length). In the general case, the user-defined
function, polyadd can be used. To use polyadd, copy the function into an m-file, and then
use it just as you would any other function in the Matlab toolbox. Assuming you had the
polyadd function stored as a m-file, and you wanted to add the two uneven polynomials, x and
y, you could accomplish this by entering the command:

z = polyadd(x,y)
x =
1 2
y =
1 4 8
z =
1 5 10

3.6 Polynomial Derivatives and Integrals


The polyder function computes the derivative of any polynomial. To obtain the derivative of
the polynomial
>> p = [1 0 -2 -5]
>> q = polyder(p)
q=
3 0 -2
polyder also computes the derivative of the product or quotient of two polynomials. For
example, create two polynomials a and b:
>> a = [1 3 5];
>> b = [2 4 6];

Calculate the derivative of the product a*b by calling polyder with a single output argument:
>>c = polyder(a,b)
c=
8 30 56 38
Calculate the derivative of the quotient a/b by calling polyder with two output arguments:
>>[q,d] = polyder(a,b)
q=
-2 -8 -2
d=
4 16 40 48 36
q/d is the result of the operation.

Polyint: Integrates polynomial analytically.

mat1-03-poly
51
G.A. El-Sheikh MATLAB: Introductory Course 52

‒ polyint(P,K) returns a polynomial representing the integral of polynomial P, using a


scalar constant of integration K.
‒ polyint(P) assumes a constant of integration K=0.
Examples:
>> p = [1 0 -2 -5];
>> polyint(p)
ans =
0.2500 0 -1.0000 -5.0000 0

>> polyint(p,2)
ans =
0.2500 0 -1.0000 -5.0000 2.0000

3.7 Partial Fraction Expansion


The command ‘residue’ finds the partial fraction expansion of the ratio of two polynomials. This
is particularly useful for applications that represent systems in transfer function form. For
polynomials b and a,

If there are no multiple roots, where r is a column vector of residues, p is a column vector of pole
locations, and k is a row vector of direct terms;
B(s) r1 r2 rn
   ..........  ks
A(s) (s  p1 ) (s  p 2 ) (s  p n )

Consider the transfer function,


b 4s 8  12 8
 2  
a s 6s 8 s  4 s 2

This transfer function can be entered to MATLAB as follows;


>> b = [-4 8];
>> a = [1 6 8];
>> [r,p,k] = residue(b,a)
r=
-12
8
p=
-4
-2
k=
[]
Given three input arguments (r, p, and k), residue converts back to polynomial form:
>> [b2,a2] = residue(r,p,k)
b2 =
-4 8
a2 =
168

mat1-03-poly
52
G.A. El-Sheikh MATLAB: Introductory Course 53

3.8 Exercises-03
1- Considering the two polynomials ( P1  s 2  2 s  1 ) and ( p 2  s  1 ); utilize MATLAB
commands to compute
a- P1*P2
b- Roots of (P1) and (P2)
c- (P1(-1)) and (P1(6))
d- (P2(-1)) and (P2(6))
2- Use MATLAB commands to find the partial fraction of the following;
N 2 s3  5 s2  3 s  6
a- P1  1  3
D1 s  6 s 2  11 s  6
N2 s2  3 s  3
b- P2  
D2 (s  1) 3

3- Use MATLAB commands to enter the following polynomials;


P1  18 s 5  25 s 4  14 s 2  32 s  35
P2  22 s 3  8 s 2  22 s  20
Then,
 Find the product (P1P2) using conv
 Find the sum (P1 + P2)
 Find the derivative of (P1)
 Find the roots of (P1)
 Find the polynomial (P1) from its roots
4- Use the MATLAB to enter the following transfer functions for further analysis:
1 10 1 1
 G1  , G2  , G3  , G4 
(s  1) (s  1) (s  2) (s  10)
1
 G5 
(s  1) (s  2)(s  3)
s  10
 G6 
(s  1) (s  2)(s  3)
9s 3
 G7 
(s  1) (s  2)(s  3)

mat1-03-poly
53
G.A. El-Sheikh MATLAB: Introductory Course 54

4- Systems of Linear Equations


4.1 Solution of Linear Equations
One of the main uses of matrices is in representing systems of linear equations. The linear
system of equations is represented by the matrix equation;
AXB
where
"A" A matrix containing the coefficients of a system of linear
equations,
"X" A column vector containing the "unknowns."
"B" A column vector of "right-hand side constant terms."

In MATLAB, solutions to the matrix equations are computed with ``matrix division''
operations. More precisely:
>> X=A\B
is the solution of A*X=B (this can be read "matrix X equals the inverse of matrix A,
multiplied by B) and,
>> X=B/A
is the solution of x*A=b.

For the case of left division, if A is square, then it is factored using Gaussian elimination and
these factors are used to solve A*x=b.

If A is not square, then it is factored using Householder orthogonalization with column


pivoting and the factors are used to solve the under- or over- determined system in the least
squares sense. Right division is defined in terms of left division by;
>> b/A=(A' \ b')'

4.2 Example-4.1
Consider a family of equations given by:
>> A = [ 3 -1 0; -1 6 -2; 0 -2 10 ];
>> B = [ 1; 5; 26 ];
The solution to these equations is given by:
>> X = A \ B
X =
1.0000
2.0000
3.0000
>>
Note that X agrees with the initial observation for the solution. This solution can be checked
by verifying that;
A*X ==> B
and A*X - B ==> 0

The required MATLAB commands are:


>> A*X
ans =
1.0
5.0

mat1-04-leqns
54
G.A. El-Sheikh MATLAB: Introductory Course 55

26.0
>> A*X - B
ans =
1.0e-14 *
0.0444
-0.2665
-0.3553
>>
Note : If there is no solution, a "least-squares" solution is provided (i.e. A*X - B is as small as
possible).

4.3 Example-4.2
Using MATLAB commands, find the solution of the following algebraic equations:
3 x 1  2 x 2  x 3  10
 x1  3 x 2  2 x 3  5
x1  x 2  x 3  1
Solution:
It is required to solve a system of 3 linear equations with 3 unknowns (x1, x2, x3).

The above equations can be put in the matrix form;


3 2 - 1  x1  10 
- 1 3 2   x    5 
   2  
1 - 1 - 1  x 3   1
That is,
AXB
 X  A 1 B
Where,
 3 2  1  x1  10 
 
A   1 3 2  , X   x 2  , B   5 
 1  1  1  x 3   1

Then, the solution can be obtained using MATLAB as follows:


Solution via Matrix Inversion: Solution via Matrix Division (left division):
>> A=[3 2 -1; -1 3 2;1 -1 -1]; >> A=[3 2 -1; -1 3 2;1 -1 -1];
>> B=[10;5;-1]; >> B=[10;5;-1];
>> X1=inv(A)*B >> X2=A\B
X1 = X2 =
-2.0000 -2.0000
5.0000 5.0000
-6.0000 -6.0000
>> >>

That is, the obtained solution has the form; x 1  2; x 2  5; x 3  6

mat1-04-leqns
55
G.A. El-Sheikh MATLAB: Introductory Course 56

4.4 Example-4.3
Engineering Application of Matrices:
In the analysis of a wide range of engineering applications, matrices are a convenient means
of representing transformations between coordinate systems, and for writing (moderate to
large) families of equations representing the state of a system (e.g. equations of equilibrium,
energy and momentum conservation, and so forth).

Suppose that the following three equations describe the equilibrium of a simple structural
system as a function of external loads and computed displacements;
3 x1  x 2  1
 x1  6 x 2  2 x3  5
 2 x 2  10 x3  26
This family of equations can be written in the form A.X = B, where
 3 1 0   x1  1 
A   1 6  2 , X   x 2  , B  5 
 0  2 10   x3  26
In a typical application, matrices A and B will be defined by the parameters of the
engineering problem, and the solution matrix X is needed to be computed. Depending on the
specific values of coefficients in matrices A and B, there may be: (a) no solutions to A.X = B,
(b) a unique solution to A.X = B, or (c) an infinite number of solutions to A.X = B. In this
particular case, however, the solution matrix is,
1 
X  2
3 
makes the right-hand side of the matrix equations (i.e., A.X) equal the left-hand side of the
matrix equations (i.e., matrix B). We will soon see how to setup and solve this family of
matrix equations in MATLAB.

mat1-04-leqns
56
G.A. El-Sheikh MATLAB: Introductory Course 57

4.5 Exercices-04
1- Use the MATLAB to generate the first 100 terms in the sequence P(n) defined recursively
by,
P(n  1)  a * P(n ) * (1  P(n )) ; with a=2.9 and P(1)=0.5.
Then plot the obtained sequence.

2- Using the MATLAB capability;


a) obtain numerical values of y(t) for which the mathematical expression is,
y0
y( t )  e  n t sin( n 1   2 * t  )
1 
b) plot y(t) for 0<t<10 with an increment of 0.1, by considering the following two cases;
 Case 1: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 3/(2√2) and  = 0;
 Case 2: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 1/(2√2) and  = 0;

3- Use the MATLAB to find the solution of the following algebraic equations:
12 x 1  14 x 2  5 x 3  10 x 4  15
5 x 2  10 x 3  14 x 4  7
 7 x1  8 x 2  6 x 3  12
 5 x 1  15 x 2  16 x 4  20

mat1-04-leqns
57
G.A. El-Sheikh MATLAB: Introductory Course 58

5- MATLAB m-Files
The objective of this chapter is to introduce you to writing M-file scripts, creating MATLAB
Functions and reviewing MATLAB flow control like ‘if-elseif-end’, ‘for loops’ and ‘while
loops’. You do not need to compile the program since MATLAB is an interpretative (not
compiled) language; such a file is called an m-file.

MATLAB is a powerful programming language as well as an interactive computational


environment. Files that contain code in the MATLAB language are called M-files. You create
M-files using a text editor, then use them as you would any other MATLAB function or
command. There are two kinds of M-files:
 Scripts, which do not accept input arguments or return output arguments. They operate on
data in the workspace. MATLAB provides a full programming language that enables you
to write a series of MATLAB statements into a file and then execute them with a single
command. You write your program in an ordinary text file, giving the file a name of
‘test01.m’. The term you use for ‘test01’ becomes the new command that MATLAB
associates with the program. The file extension of .m makes this a MATLAB M-file.
 Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.

Just create the M-files that you want to try out in the current directory. As you develop more
of your own M-files, you will want to organize them into other directories and personal
toolboxes that you can add to your MATLAB search path. If you duplicate function names,
MATLAB executes the one that occurs first in the search path. To view the contents of an M-
file, for example, test01.m, use
>> type test01

Functions and scripts are both M-files, but there are a few differences between them. As we
saw, the first line defines whether the M-file is a function or a script. A function has a
particular set of inputs and outputs, while a script doesn’t. A script can use all the variables
created in the MATLAB workspace, but a function can only use the variables specially passed
to it. After the execution is over, a script returns all the variables to the workspace while a
function only returns the variables listed as outputs and deletes the rest of the variables.

Scripts use the same copy of a variable in the MATLAB workspace and modifying any
variable in any script will affect the original copy in the workspace while a function creates a
new copy of all the variables when they are called and any modification to these variables
doesn’t affect the original variables. In other words, when a function is called from a
workspace, the function call creates a new workspace, copies variables to it, computes outputs
and returns these variables to the calling workspace, deleting its own workspace. You can also
call a script from a function. In that case, the script will use the calling function’s workspace
and the variables created by this script call will also get deleted when the calling function
finishes its execution.

5.1 Constructing a Program in MATLAB


This list summarizes the steps for writing your first MATLAB program:
1. Start the MATLAB desktop via the Windows Start menu or by double clicking on the
MATLAB icon on the desktop.
2. Click on File-New-Script; This brings up a new Script window.
3. Type your script into the Script window.

mat1-05-files
58
G.A. El-Sheikh MATLAB: Introductory Course 59

4. Save the script by clicking on the Save icon in the icon toolbar or clicking on File in the
menu bar and selecting Save in the drop down menu. In the dialog box that appears,
select the folder where the script is to reside and type in a file name of your own
choosing. It is best to use a folder that contains only your own MATLAB scripts.
5. Before you can run your script, you need to go to the Current Folder box at the top of the
MATLAB desktop, clicking on the down arrow and in the drop down menu, selecting (or
browsing to) the folder that contains your new script.
6. You may run your script from the Script window by clicking on the Save and Run green
arrow in the icon toolbar or alternatively, from the command window by typing the script
name (without the .m extension) after the MATLAB prompt (>>).

For example, if the program has been saved as circuit.m, then type circuit after the MATLAB
prompt (>>), as shown below:
>> circuit
If you need additional help getting
started, you can click on Help in the
menu bar in the MATLAB window and
then select Product Help from the drop-
down menu. This will bring up the help
window as shown in Fig. 5.1a. By
clicking on the little ‘+’ box next to the
MATLAB listing in the left column,
you will get additional help topics as
shown in Fig. 5.1b. Once you select one
of the help topics, the help information
will be in the right-hand window. You
can also type in a topic in the search
window to obtain information on that
topic. Fig. 5.1a

Fig. 5.1b

mat1-05-files
59
G.A. El-Sheikh MATLAB: Introductory Course 60

5.1 Program Development with M-Files


MATLAB statements can be prepared with any editor, and stored in a file for later use. Such a
file is referred to as a script, or an "m-file" (since they must have a name extension of the
form filename.m). Writing m-files will enhance your problem solving productivity.
Suppose that we create a program file
myfile.m
in the MATLAB language. The commands in this file can be executed by simply giving the
command
>> myfile
from MATLAB. The MATLAB statements will run like any other MATLAB function. You
do not need to compile the program since MATLAB is an interpretative (not compiled)
language.
An M-file can reference other M-files, including referencing itself recursively.

5.1.1 Example-5.1
Using your favorite editor, create the following file, named sketch.m:
clc
clear
[x y] = meshgrid(-3:.1:3, -3:.1:3);
z = x.^2 - y.^2;
mesh(x,y,z);
Then start MATLAB from the directory containing this file, and enter
>> sketch
The result is the same as if you had entered the three lines of the file, at the prompt, see Fig.
5.1.

10

-5

-10
4
2 4
0 2
0
-2 -2
-4 -4
Fig. 5.1: Mesh generated by commands in M-file sketch.m

mat1-05-files
60
G.A. El-Sheikh MATLAB: Introductory Course 61

5.1.2 Example-5.2
You can also enter data this way: if a file named mymatrix.m in the current working directory
contains the lines
A = [2 3 4; 5 6 7; 8 9 0]
inv(A)
quit
then the command
>> mymatrix
reads that file, generates A and the inverse of A, and quits MATLAB [quitting is optional].
You may prefer to do this, if you use the same data repeatedly, or have an editor that you like
to use. You can use Control-Z to suspend MATLAB, then edit the file, and then use "fg" to
bring matlab back to the foreground, to run it.

5.1.3 M-File Examples


MATLAB comes with a lot of "m-file" examples! To find their location on your computer,
use
>> path
This will also lead you to some really nifty demos.

5.1.4 Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts
can operate on existing data in the workspace, or they can create new data on which to
operate. Although scripts do not return output arguments, any variables that they create
remain in the workspace, to be used in subsequent computations. In addition, scripts can
produce graphical output using functions like plot.

Example:
Create a file called ‘test01.m’ that contains these MATLAB commands:
% Create random numbers and plot these numbers
clc
clear
r = rand(1,50)
plot(r)
Typing the statement ‘test01’ at command prompt causes MATLAB to execute the
commands, creating fifty random numbers and plots the result in a new window. After
execution of the file is complete, the variable ‘r’ remains in the workspace.

Example:
The following statements calculate rho for several trigonometric functions of theta, then
create a series of polar plots:
% An M-file script to produce % Comment lines
% "flower petal" plots
theta = -pi:0.01:pi; % Computations
rho(1,:) = 2*sin(5*theta).^2;
rho(2,:) = cos(10*theta).^3;
rho(3,:) = sin(theta).^2;
rho(4,:) = 5*cos(3.5*theta).^3;
for i = 1:4
polar(theta,rho(i,:)) % Graphics output
pause
end

mat1-05-files
61
G.A. El-Sheikh MATLAB: Introductory Course 62

Try entering these commands in an M-file called test02.m; this file is now a MATLAB
script. Typing test02 at the MATLAB command line executes the statements in the script.
After the script displays a plot, press Return to move to the next plot. There are no input or
output arguments; test02 creates the variables it needs in the MATLAB workspace. When
execution completes, the variables (i, theta, and rho) remain in the workspace.

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts
can operate on existing data in the workspace, or they can create new data on which to
operate. Although scripts do not return output arguments, any variables that they create
remain in the workspace, to be used in subsequent computations. In addition, scripts can
produce graphical output using functions like plot.

Example:
Create a file called magicrank.m that contains these MATLAB commands.
% Investigate the rank of magic squares
r = zeros(1,32);
for n = 3:32
r(n) = rank(magic(n));
end
r
bar(r)

Typing the statement


>> magicrank
causes MATLAB to execute the
commands, compute the rank of the first
30 magic squares, and plot a bar graph of
the result. After execution of the file is
complete, the variables n and r remain in
the workspace.

5.3 Function Files


Function files provide extensibility to MATLAB by allowing you to create new problem-
specific functions having the same status as other built-in MATLAB functions. Functions are
like scripts, but for the purposes of computational speed, are compiled the first time.

Functions are M-files that can accept input arguments and return output arguments. The
names of the M-file and of the function should be the same. Functions operate on variables
within their own workspace, separate from the workspace you access at the MATLAB
command prompt.

Example:
function f = fact(n) % Function definition line
% Compute a factorial value. % H1 line
% FACT(N) returns the factorial of N, % Help text
% usually denoted by N!

% Put simply, FACT(N) is PROD(1:N). % Comment


f = prod(1:n); % Function body

mat1-05-files
62
G.A. El-Sheikh MATLAB: Introductory Course 63

M-File Element Description


Function definition line Defines the function name, and the number and order of input and
(functions only) output arguments.
H1 line A one line summary description of the program, displayed when you
request help on an entire directory, or when you use ‘lookfor’.
Help text A more detailed description of the program, displayed together
with the H1 line when you request help on a specific function
Function or script body Program code that performs the actual computations and assigns
values to any output arguments.
Comments Text in the body of the program that explains the internal workings of
the program.

The first line of a function M-file starts with the keyword ‘function’. It gives the function
name and order of arguments. In this case, there is one input arguments and one output
argument. The next several lines, up to the first blank or executable line, are comment lines
that provide the help text. These lines are printed when you type ‘help fact’. The first line of
the help text is the H1 line, which MATLAB displays when you use the ‘lookfor’ command
or request help on a directory. The rest of the file is the executable MATLAB code defining
the function.

The variable n & f introduced in the body of the function as well as the variables on the first
line are all local to the function; they are separate from any variables in the MATLAB
workspace. This example illustrates one aspect of MATLAB functions that is not ordinarily
found in other programming languages; a variable number of arguments. Many M-files work
this way. If no output argument is supplied, the result is stored in ans. If the second input
argument is not supplied, the function computes a default value.

Example-5.3
Here we create a file named "sqroot.m" containing the following lines;
function sqroot(x)
% SQROOT Compute square root by Newton's method

% Initial guess
xstart = 1;

% Iteration loop to compute square root


for i = 1:100
xnew = ( xstart + x/xstart)/2;
disp(xnew);
if abs(xnew - xstart)/xnew < eps, break, end;
xstart = xnew;
end

The first line declares the function name, input arguments, and output arguments; without this
line the file would be a script file. Notice that the file name corresponds to the function name.
Variables in a function file are local by default.
The first few lines of a function should be comment statements so that they can be used in
online-help e.g.,
>> help sqroot

mat1-05-files
63
G.A. El-Sheikh MATLAB: Introductory Course 64

SQROOT Compute square root by Newton's method


>>
With the function m-file in place, we can give the MATLAB commands
>> format long
>> sqroot(20)
and the square root of 20 will be computed, as in
>> sqroot(20)
10.50000000000000
6.20238095238095
4.71347454528837
4.47831444547438
4.47214021706570
4.47213595500161
4.47213595499958
4.47213595499958
>>

Example-5.4
A function may have multiple output arguments. For example:
function [mean, stdev] = stat(x)

% STAT Mean and standard deviation


% For a vector x, stat(x) returns the
% mean and standard deviation of x.
% For a matrix x, stat(x) returns two row vectors containing,
% respectively, the mean and standard deviation of each column.

[m n] = size(x);
if m == 1
m = n; % handle case of a row vector
end
mean = sum(x)/m;
stdev = sqrt(sum(x.^ 2)/m - mean.^2);

Notice that mean and stdev are both computed inside the function body.
Once this is placed in the m-file stat.m, a MATLAB command
>> [xm, xd] = stat(x)
will assign the mean and standard deviation of the entries in the vector x to xm and xd,
respectively.

For example, the script of code:


>> y = [1:10];
>> [ym, yd] = stat(y)

ym =
5.5000

yd =
2.8723

>>
shows computation of the mean and standard deviation of the integers one through ten.
Single assignments can also be made with a function having multiple output arguments.
For example,
>> xm = stat(x)

mat1-05-files
64
G.A. El-Sheikh MATLAB: Introductory Course 65

(no brackets needed around xm) will assign the mean of x to xm.

Example-5.5
The following function, which gives the greatest common divisor of two integers via the
Euclidean algorithm, illustrates the use of an error message.
function a = gcd(a,b)

% GCD Greatest common divisor


% gcd(a,b) is the greatest common divisor of
% the integers a and b, not both zero.

a = round(abs(a));
b = round(abs(b));

if a == 0 & b == 0
error('The gcd is not defined when both numbers are zero')
else
while b ~= 0
r = rem(a,b);
a = b; b = r;
end
end
For example,
>> a = gcd (25,45)

a =
5

>>
The prime factorizations of 25 and 45 are 5.5 and 5.3.3, and so the greatest common divisor is
5.

Example:
A good example is provided by rank; the M-file rank.m is available in the directory
toolbox/matlab/matfun
You can see the file with
type rank
Here is the file;
function r = rank(A,tol)
% RANK Matrix rank.
% RANK(A) provides an estimate of the number of linearly
% independent rows or columns of a matrix A.
% RANK(A,tol) is the number of singular values of A
% that are larger than tol.
% RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.

s = svd(A);
if nargin==1
tol = max(size(A)') * max(s) * eps;
end
r = sum(s > tol);

The first line of a function M-file starts with the keyword function. It gives the function name
and order of arguments. In this case, there are up to two input arguments and one output
argument.

mat1-05-files
65
G.A. El-Sheikh MATLAB: Introductory Course 66

The next several lines, up to the first blank or executable line, are comment lines that provide
the help text. These lines are printed when you type
>> help rank
The first line of the help text is the H1 line, which MATLAB displays when you use the
lookfor command or request help on a directory.

The rest of the file is the executable MATLAB code defining the function. The variable s
introduced in the body of the function, as well as the variables on the first line, r, A and tol,
are all local to the function; they are separate from any variables in the MATLAB workspace.

This example illustrates one aspect of MATLAB functions that is not ordinarily found in
other programming languages; a variable number of arguments. The rank function can be
used in several different ways.
>> rank(A)
>> r = rank(A)
>> r = rank(A,1.e-6)

Many M-files work this way; If no output argument is supplied, the result is stored in ans. If
the second input argument is not supplied, the function computes a default value.

Within the body of the function, two quantities named nargin and nargout are available which
tell you the number of input and output arguments involved in each particular use of the
function. The rank function uses nargin, but does not need to use nargout.

Global Variables
If you want more than one function to share a single copy of a variable, simply declare the
variable as global in all the functions. Do the same thing at the command line if you want the
base workspace to access the variable. The global declaration must occur before the variable
is actually used in a function. Although it is not required, using capital letters for the names of
global variables helps distinguish them from other variables.

Example:
Create an M-file called test05.m;
function h1 = test05(t)
global G1
h1 = 1/2*G1*t1.^2;

Then interactively enter the statements;


global G1
G1 = 32;
Y1 = test05((0:0.1:5)');
The two global statements make the value assigned to G1 at the command prompt available
inside the function. You can then modify G1 interactively and obtain new solutions without
editing any file.

5.4 Batch Jobs


MATLAB is most often used interactively, but "batch" or "background" jobs can be
performed as well. Debug your commands interactively and store them in a file (`script.m', for
example). To start a background session from your input file and to put the output and error
messages into another file (`script.out', for example), enter this line at the system prompt:

mat1-05-files
66
G.A. El-Sheikh MATLAB: Introductory Course 67

nice matlab < script.m >& script.out &

You can then do other work at the machine or logout while MATLAB grinds out your
program. Here's an explanation of the sequence of commands above.
1. The "nice" command lowers matlab's priority so that interactive users have first crack
at the CPU. You must do this for noninteractive MATLAB sessions because of the
load that number--crunching puts on the CPU.
2. The "< script.m" means that input is to be read from the file script.m. Details on
scripting-files may be found below.
3. The ">& script.out" is an instruction to send program output and error output to the
file script.out.
It is important to include the first ampersand (&) so that error messages are sent to
your file rather than to the screen -- if you omit the ampersand then your error
messages may turn up on other people's screens and your popularity will plummet.)
4. Finally, the concluding ampersand (&) puts the whole job into background.

Of course, the file names used above are not important; these are just examples to illustrate
the format of the command string.

5.5 Detailed Functions


Functions are M-files that accept input arguments and return output arguments. They operate
on variables within their own workspace. This is separate from the workspace you access at
the MATLAB command prompt.

5.5.1 Simple Function Example


The average function is a simple M-file that calculates the average of the elements in a
vector;
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Non-vector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')
end
y = sum(x)/length(x); % Actual computation

If you would like, try entering these commands in an M-file called average.m. The
average function accepts a single input argument and returns a single output argument. To
call the average function, enter
>> z = 1:99;
>> average(z)

ans =
50

mat1-05-files
67
G.A. El-Sheikh MATLAB: Introductory Course 68

5.5.2 Basic Parts of a Function M-File


The Function Definition Line
The function definition line informs MATLAB
that the M-file contains a function, and specifies
the argument calling sequence of the function.
The function definition line for the average
function is shown in schematic.

All MATLAB functions have a function definition line that follows this pattern. If the
function has multiple output values, enclose the output argument list in square brackets. Input
arguments, if present, are enclosed in parentheses. Use commas to separate multiple input or
output arguments. Here's a more complicated example.
function [x,y,z] = sphere(theta,phi,rho)

If there is no output, leave the output blank


function printresults(x)
or use empty square brackets
function [] = printresults(x)
The variables that you pass to the function do not need to have the same name as those in the
function definition line.

The H1 Line
The H1 line, so named because it is the first help text line, is a comment line immediately
following the function definition line. Because it consists of comment text, the H1 line begins
with a percent sign, "%." For the average function, the H1 line is
% AVERAGE Mean of vector elements.
This is the first line of text that appears when a user types help function_name at the
MATLAB prompt. Further, the lookfor function searches on and displays only the H1 line.
Because this line provides important summary information about the M-file, it is important to
make it as descriptive as possible.

Help Text
You can create online help for your M-files by entering text on one or more comment lines,
beginning with the line immediately following the H1 line. The help text for the average
function is
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Nonvector input results in an error.

When you type help function_name, MATLAB displays the comment lines that appear
between the function definition line and the first non-comment (executable or blank) line. The
help system ignores any comment lines that appear after this help block.
For example, typing help sin results in
SIN Sine.
SIN(X) is the sine of the elements of X.

The Function Body


The function body contains all the MATLAB code that performs computations and assigns
values to output arguments. The statements in the function body can consist of function calls,

mat1-05-files
68
G.A. El-Sheikh MATLAB: Introductory Course 69

programming constructs like flow control and interactive input/output, calculations,


assignments, comments, and blank lines.

For example, the body of the average function contains a number of simple programming
statements.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) % Flow control
error('Input must be a vector') % Error message display
end
y = sum(x)/length(x); % Computation and assignment

Comments
As mentioned earlier, comment lines begin with a percent sign ( %). Comment lines can appear
anywhere in an M-file, and you can append comments to the end of a line of code. For
example,
% Add up all the vector elements.
y = sum(x) % Use the sum function.
The first comment line immediately following the function definition line is considered the
H1 line for the function. The H1 line and any comment lines immediately following it
constitute the online help entry for the file. In addition to comment lines, you can insert blank
lines anywhere in an M-file. Blank lines are ignored. However, a blank line can indicate the
end of the help text entry for an M-file.

5.5.3 Function Names


MATLAB function names have the same constraints as variable names. MATLAB uses the
first 31 characters of names. Function names must begin with a letter; the remaining
characters can be any combination of letters, numbers, and underscores. Some operating
systems may restrict function names to shorter lengths. The name of the text file that contains
a MATLAB function consists of the function name with the extension .m appended. For
example,
average.m

If the filename and the function definition line name are different, the internal name is
ignored. Thus, while the function name specified on the function definition line does not have
to be the same as the filename, we strongly recommend that you use the same name for both.

5.5.4 How Functions Work


You can call function M-files from either the MATLAB command line or from within other
M-files. Be sure to include all necessary arguments, enclosing input arguments in parentheses
and output arguments in square brackets.

Function Name Resolution


When MATLAB comes upon a new name, it resolves it into a specific function by following
these steps:
1. Checks to see if the name is a variable.
2. Checks to see if the name is a subfunction, a MATLAB function that resides in the
same M-file as the calling function. Subfunctions are discussed in the section,
Subfunctions.

mat1-05-files
69
G.A. El-Sheikh MATLAB: Introductory Course 70

3. Checks to see if the name is a private function, a MATLAB function that resides in a
private directory, a directory accessible only to M-files in the directory immediately
above it. Private directories are discussed in the section, Private Functions.
4. Checks to see if the name is a function on the MATLAB search path. MATLAB uses
the first file it encounters with the specified name.

If you duplicate function names, MATLAB executes the one found first using the above rules.
It is also possible to overload function names. This uses additional dispatching rules and is
discussed in the section, How MATLAB Determines Which Method to Call.

What Happens When You Call a Function


When you call a function M-file from either the command line or from within another M-file,
MATLAB parses the function into pseudocode and stores it in memory. This prevents
MATLAB from having to reparse a function each time you call it during a session. The
pseudocode remains in memory until you clear it using the clear function, or until you quit
MATLAB. You can use clear in any of the following ways to remove functions from the
MATLAB workspace.
Syntax Description
clear function_name Remove specified function from workspace

clear functions Remove all compiled M-functions


clear all Remove all variables and functions

Creating P-Code Files


You can save a preparsed version of a function or script, called P-code files, for later
MATLAB sessions using the pcode function.
For example,
pcode average
parses average.m and saves the resulting pseudocode to the file named average.p. This
saves MATLAB from reparsing average.m the first time you call it in each session.
MATLAB is very fast at parsing so the pcode function rarely makes much of a speed
difference. One situation where pcode does provide a speed benefit is for large GUI
applications. In this case, many M-files must be parsed before the application becomes
visible. Another situation for pcode is when, for proprietary reasons, you want to hide
algorithms you've created in your M-file.

How MATLAB Passes Function Arguments


From the programmer's perspective, MATLAB appears to pass all function arguments by
value. Actually, however, MATLAB passes by value only those arguments that a function
modifies. If a function does not alter an argument but simply uses it in a computation,
MATLAB passes the argument by reference to optimize memory use.

Function Workspaces
Each M-file function has an area of memory, separate from MATLAB's base workspace, in
which it operates. This area is called the function workspace, with each function having its
own workspace context. While using MATLAB, the only variables you can access are those
in the calling context, be it the base workspace or that of another function. The variables that
you pass to a function must be in the calling context, and the function returns its output

mat1-05-files
70
G.A. El-Sheikh MATLAB: Introductory Course 71

arguments to the calling workspace context. You can however, define variables as global
variables explicitly, allowing more than one workspace context to access them.

5.5.5 Checking the Number of Function Arguments


The nargin and nargout functions let you determine how many input and output arguments a
function is called with. You can then use conditional statements to perform different tasks
depending on the number of arguments. For example,
function c = testarg1(a,b)
if (nargin == 1)
c = a.^2;
elseif (nargin == 2)
c = a + b;
end

Given a single input argument, this function squares the input value. Given two inputs, it adds
them together.

Here's a more advanced example that finds the first token in a character string. A token is a set
of characters delimited by whitespace or some other character. Given one input, the function
assumes a default delimiter of whitespace; given two, it lets you specify another delimiter if
desired. It also allows for two possible output argument lists;
function [token,remainder] = strtok(string,delimiters)
% Function requires at least one input argument
if nargin < 1
error('Not enough input arguments.');
end
token = []; remainder = [];
len = length(string);
if len == 0
return
end

% If one input, use white space delimiter


if (nargin == 1)
delimiters = [9:13 32]; % White space characters
end
i = 1;

% Determine where non-delimiter characters begin


while (any(string(i) == delimiters))
i = i + 1;
if (i > len), return, end
end

% Find where token ends


start = i;
while (~any(string(i) == delimiters))
i = i + 1;
if (i > len), break, end
end

mat1-05-files
71
G.A. El-Sheikh MATLAB: Introductory Course 72

finish = i - 1;
token = string(start:finish);

% For two output arguments, count characters after


% first delimiter (remainder)
if (nargout == 2)
remainder = string(finish + 1:end);
end

The strtok function is a MATLAB M-file in the strfun directory.


The order in which output arguments appear in the function declaration line is important. The
argument that the function returns in most cases appears first in the list. Additional, optional
arguments are appended to the list.

5.5.6 Passing Variable Numbers of Arguments


The varargin and varargout functions let you pass any number of inputs or return any number
of outputs to a function. This section describes how to use these functions and also covers:
 Unpacking varargin Contents
 Packing varargout Contents
 varargin and varargout in Argument Lists

MATLAB packs all specified input arguments into a cell array, a special kind of MATLAB
array that consists of cells instead of array elements. Each cell can hold any size or kind of
data - one might hold a vector of numeric data, another in the same array might hold an array
of string data, and so on. For output arguments, your function code must pack them into a cell
array so that MATLAB can return the arguments to the caller. Here's an example function that
accepts any number of two-element vectors and draws a line to connect them.
function testvar(varargin)
for i = 1:length(varargin)
x(i) = varargin{i}(1); % Cell array indexing
y(i) = varargin{i}(2);
end
xmin = min(0,min(x));
ymin = min(0,min(y));
axis([xmin fix(max(x))+3 ymin fix(max(y))+3])
plot(x,y)
Coded this way, the testvar function works with various input lists; for example,
testvar([2 3],[1 5],[4 8],[6 5],[4 2],[2 3])
testvar([-1 0],[3 -5],[4 2],[1 1])

Unpacking varargin Contents


Because varargin contains all the input arguments in a cell array, it's necessary to use cell
array indexing to extract the data. For example,
y(i) = varargin{i}(2);
Cell array indexing has two subscript components:
 The cell indexing expression, in curly braces
 The contents indexing expression(s), in parentheses
In the code above, the indexing expression {i} accesses the i'th cell of varargin. The
expression (2) represents the second element of the cell contents.

Packing varargout Contents

mat1-05-files
72
G.A. El-Sheikh MATLAB: Introductory Course 73

When allowing any number of output arguments, you must pack all of the output into the
varargout cell array. Use nargout to determine how many output arguments the function is
called with. For example, this code accepts a two-column input array, where the first column
represents a set of x coordinates and the second represents y coordinates. It breaks the array
into separate [xi yi] vectors that you can pass into the testvar function on the previous
page.
function [varargout] = testvar2(arrayin)
for i = 1:nargout
varargout{i} = arrayin(i,:) % Cell array assignment
end
The assignment statement inside the for loop uses cell array assignment syntax. The left side
of the statement, the cell array, is indexed using curly braces to indicate that the data goes
inside a cell. For complete information on cell array assignment, see the Structures and Cell
Arrays section.
Here's how to call testvar2.
a = {1 2;3 4;5 6;7 8;9 0};
[p1,p2,p3,p4,p5] = testvar2(a);

varargin and varargout in Argument Lists


varargin or varargout must appear last in the argument list, following any required input or
output variables. That is, the function call must specify the required arguments first. For
example, these function declaration lines show the correct placement of varargin and
varargout.
function [out1,out2] = example1(a,b,varargin)
function [i,j,varargout] = example2(x1,y1,x2,y2,flag)

5.5.7 Local and Global Variables


The same guidelines that apply to MATLAB variables at the command line also apply to
variables in M-files:
 You do not need to type or declare variables. Before assigning one variable to another, however,
you must be sure that the variable on the right-hand side of the assignment has a value.
 Any operation that assigns a value to a variable creates the variable if needed, or overwrites its
current value if it already exists.
 MATLAB variable names consist of a letter followed by any number of letters, digits, and
underscores. MATLAB distinguishes between uppercase and lowercase characters, so A and a
are not the same variable.
 MATLAB uses only the first 31 characters of variable names.

Ordinarily, each MATLAB function, defined by an M-file, has its own local variables, which
are separate from those of other functions, and from those of the base workspace. However, if
several functions, and possibly the base workspace, all declare a particular name as global,
then they all share a single copy of that variable. Any assignment to that variable, in any
function, is available to all the other functions declaring it global.
Suppose you want to study the effect of the interaction coefficients, and , in the Lotka-
Volterra predator-prey model.

Create an M-file, lotka.m.


function yp = lotka(t,y)
%LOTKA Lotka-Volterra predator-prey model.
global ALPHA BETA

mat1-05-files
73
G.A. El-Sheikh MATLAB: Introductory Course 74

yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];

Then interactively enter the statements


global ALPHA BETA
ALPHA = 0.01
BETA = 0.02
[t,y] = ode23('lotka',0,10,[1; 1]);
plot(t,y)

The two global statements make the values assigned to ALPHA and BETA at the command
prompt available inside the function defined by lotka.m. They can be modified interactively
and new solutions obtained without editing any files.
For your MATLAB application to work with global variables:
 Declare the variable as global in every function that requires access to it. To enable the
workspace to access the global variable, also declare it as global from the command
line.
 In each function, issue the global command before the first occurrence of the variable
name. The top of the M-file is recommended.

MATLAB global variable names are typically longer and more descriptive than local variable
names, and sometimes consist of all uppercase characters. These are not requirements, but
guidelines to increase the readability of MATLAB code and reduce the chance of accidentally
redefining a global variable.

mat1-05-files
74
G.A. El-Sheikh MATLAB: Introductory Course 75

5.6 Exercises-05
1- Use the MATLAB to generate the first 100 terms in the sequence P(n) defined recursively
by,
P(n  1)  a * P(n ) * (1  P(n )) ; with a=2.9 and P(1)=0.5.
Then plot the obtained sequence.

2- Using the MATLAB M-file Function capability;

a) Write a MATLAB M-file function to obtain numerical values of y(t). The function must
take y(0), ζ, ωn, t and  as function inputs and y(t) as output argument. The mathematical
expression is
y0
y( t )  e  n t sin( n 1   2 * t  )
1 
b) Write a second script m-file to obtain the plot for y(t) for 0<t<10 with an increment of 0.1,
by considering the following two cases;
 Case 1: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 3/(2√2) and  = 0;
 Case 2: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 1/(2√2) and  = 0;

Hint: When you write the function you would require element-by-element operator

3- Use the MATLAB ‘for’ or ‘while’ loop to convert degrees Fahrenheit (T f) to degrees
Celsius using the following equation;
9
Tf  * Tc  32
5
Use any starting temperature, increment and ending temperature (example: starting
temperature=0, increment=10, ending temperature = 200).

4- Write a program using function which accept two integers as an argument and return its
sum. Call this function from a driver and print the results.
5- Write a function to calculate the factorial value of any integer as an argument. Call this
function from driver and print the results.
6- Write a function that receives two numbers as an argument and display all prime numbers
between these two numbers. Call this function from driver.
7- Raising a number to a power p is the same as multiplying n by itself p times. Write a
function called power that takes two arguments, a double value for n and an int value for p,
and return the result as double value. Use default argument of 2 for p, so that if this
argument is omitted the number will be squared. Write the main function that gets value
from the user to test power function.
8- Write a function called zero_small() that has two integer arguments being passed by
reference and sets the smaller of the two numbers to 0. Write the main program to access
the function.
9- Write a program that lets the user perform arithmetic operations on two numbers. Your
program must be menu driven, allowing the use to select the operation (+, -, *, or /) and
input the numbers. Furthermore, your program must consist of following functions:
 Function showChoice: This function shows the options to the user and explains how to enter
data
 Function add: This function accepts two number as arguments and returns sum
 Function subtract: This function accepts two number as arguments and returns their difference
 Function multiply: This function accepts two number as arguments and returns product

mat1-05-files
75
G.A. El-Sheikh MATLAB: Introductory Course 76

 Function divide: This function accepts two number as arguments and returns quotient

10-a) Write a MATLAB program to calculate and display the Fibonacci sequence;
F(n )  F(n  1)  F(n  2)
-b) Write a MATLAB program to calculate and display the Factorial of a number;
N! (1) (2) ........ ( N  1) ( N)
-c) Write a MATLAB program to calculate and display the Sequence G1(n);
F(n ) F(n  1)  F(n  2)
G1(n )  
n! n!

11- Using MATLAB, design a program to find the solution of the following algebraic
equations:
12 x 1  14 x 2  5 x 3  10 x 4  15
5 x 2  10 x 3  14 x 4  7
 7 x1  8 x 2  6 x 3  12
 5 x 1  15 x 2  16 x 4  20

12-- Design a MATLAB program to enter the following polynomials;


P1  18 s 5  25 s 4  14 s 2  32 s  35
P2  22 s 3  8 s 2  22 s  20
Then,
 Find the product (P1P2) using conv
 Find the sum (P1 + P2) using any of the flow-control commands
 Find the derivative of (P1)
 Find the roots of (P1)
 Find the polynomial (P1) from its roots

13-a) Using MATLAB, design a program to calculate and plot the function (with appropriate
axes and legends);
F1  sin( t )  e t
Where,
−  = 2  f, f = 2 Hz, t = time history (0 to 3 [sec])

14-b) Using MATLAB, design a program to;


− Generate a certain function (as you want) and save it in a data-file,
− Load the data/set of measurements,
− Plot this data with necessary labels,
− Find the maximum and minimum values,
− Find the average value, and
− Display the obtained information in a good format.

mat1-05-files
76
G.A. El-Sheikh MATLAB: Introductory Course 77

6- Flow Control Structures


Control-of-flow in MATLAB programs is achieved with logical/relational constructs,
branching constructs, and a variety of looping constructs.

6.1 Colon Notation


A central part of the MATLAB language syntax is the "colon operator," which produces a list.
For example:
>> format compact
>> -3:3
ans =
-3 -2 -1 0 1 2 3
The default increment is by 1, but that can be changed. For example:
>> x = -3 : .3 : 3
x =
Columns 1 through 7
-3.0000 -2.7000 -2.4000 -2.1000 -1.8000 -1.5000 -1.2000
Columns 8 through 14
-0.9000 -0.6000 -0.3000 0 0.3000 0.6000 0.9000
Columns 15 through 21
1.2000 1.5000 1.8000 2.1000 2.4000 2.7000 3.0000
>>
This can be read: "x is the name of the list, which begins at -3, and whose entries increase by
.3, until 3 is surpassed." You may think of x as a list, a vector, or a matrix, whichever you
like.

The following statements generate a table of sines;


>> x = [0.0:0.1:2.0]' ;
>> y = sin(x);
>> [x y]
Try it. Note that since sin operates entry-wise, it produces a vector y from the vector x.
The colon notation can also be combined with the earlier method of constructing matrices.
>> a = [1:6 ; 2:7 ; 4:9]

Matlab offers some powerful methods for creating arrays and for taking them apart;
>> x= -2:1
>> length(x)
>> y = -2:0.5:1
>> a=magic(5)
>> a(2,3)

Now you can use the colon notation to select a column of a;


>> a(2,:)
>> a(:,3)
>> a
>> a(2:4,:)
>> a(:,3:5)
>> a(2:4,3:5)
>> a(1:2:5,:)

You can put a vector into a row or column position within a as follows;
>> a(:,[1 2 5])

mat1-06-flow-control
77
G.A. El-Sheikh MATLAB: Introductory Course 78

>> a([2 5],[2 4 5])

You can also make assignment statements using a vector or a matrix;


>> b=rand(5)
>> b([1 2],:) = a([1 2],:)
>> a(:,[1 2]) = b(:,[3 5])
>> a(:,[1 5]) = a(:,[5 1])
>> a = a(:,5:-1:1)

When you a insert a 0-1 vector into the column position then the columns which correspond
to 1's are displayed;
>> v=[0 1 0 1 1]
>> a(:,v)
>> a(v,:)

This is a sample of the basic MATLAB functions and the matrix manipulation techniques that
will be matured through the rest of the book.

6.2 Relational and Logical Constructs


The relational operators in MATLAB are,
Operator Description
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
~= not equal
Note that ``='' is used in an assignment statement while ``=='' is used in a relation.

Relations may be connected or quantified by the logical operators;


Operator Description
& and
| or
~ not

When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the
relation is true or false (indeed, throughout this section you should think of 1 as true and 0 as
false).
For example;
>> 3 < 5
ans =
1
>> a = 3 == 5
a =
0
>>

When logical operands are applied to matrices of the same size, a relation is a matrix of 0's
and 1's giving the value of the relation between corresponding entries.

mat1-06-flow-control
78
G.A. El-Sheikh MATLAB: Introductory Course 79

For example:
>> A = [ 1 2; 3 4 ];
>> B = [ 6 7; 8 9 ];
>> A == B
ans =
0 0
0 0
>> A < B
ans =
1 1
1 1
>>
To see how the other logical operators work, you should also try
>> ~A
>> A&B
>> A & ~B
>> A | B
>> A | ~A
The for statement permits any matrix to be used instead of 1:n.

There is a function to determine if a matrix has at least one nonzero entry (any) as well as a
function to determine if all the entries are nonzero (all);
>> a=[1 0 1 0]
>> b=[1 1 0 0]
>> any(a)
>> c = zeros(1,4)
>> d = ones(1,4)
>> any(c)
>> all(a)
>> all(d)
>> e=[a',b',c',d']
>> any(e)
>> all(e)
>> any(all(e))

6.3 Branching Constructs


MATLAB provides a number of language-constructs for branching a program's control of
flow. There are eight flow control or branching statements as follows:
 if, together with else and elseif, executes a group of statements based on some logical
condition.
 switch, together with case and otherwise, executes different groups of statements
depending on the value of some logical condition.
 while executes a group of statements an indefinite number of times, based on some
logical condition.
 for executes a group of statements a fixed number of times.
 continue passes control to the next iteration of a for or while loop, skipping any
remaining statements in the body of the loop.
 break terminates execution of a for or while loop.
 try...catch changes flow control if an error is detected during execution.
 return causes execution to return to the invoking function.

mat1-06-flow-control
79
G.A. El-Sheikh MATLAB: Introductory Course 80

All flow constructs use end to indicate the end of the flow control block. You can often speed
up the execution of MATLAB code by replacing for and while loops with vectorized code.

Branching is the construction;


if <condition>, <program> end

The condition is a MATLAB function usually, but not necessarily with values 0 or 1 and the
entire construction allows the execution of the program just in case the value of condition is
not 0. If that value is 0, the control moves on to the next program construction. You should
keep in mind that MATLAB regards a==b and a<=b as functions with values 0 or 1.

Frequently, this construction is elaborated with;


if <condition1>, <program1> else <program2> end
In this case if condition is 0, then program2 is executed.
Another variation is
if <condition1>, <program1>
elseif <condition2>, <program2>
end
Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is
not 0, then program2 is executed, and otherwise control is passed on to the next construction.
Here is a short program to illustrate branching.
function b=even(n)

% b=even(n). If n is an even integer, then b=1


% otherwise, b=0.

if mod(n,2)==0,
b=1;
else b=0;
end

6.3.1 If-end Construct


This section covers those MATLAB functions that provide conditional program control. if,
else, and elseif. The if-statement evaluates a logical expression and executes a group of
statements when the expression is true. The optional elseif and else keywords provide for the
execution of alternate groups of statements. An end keyword, which matches the if,
terminates the last group of statements.

The groups of statements are delineated by the four keywords; no braces or brackets are
involved as given below;
if <condition>
<statements>;
elseif <condition>
<statements>;
else
<statements>;
end

It is important to understand how relational operators and if statements work with matrices.
When you want to check for equality between two variables, you might use

mat1-06-flow-control
80
G.A. El-Sheikh MATLAB: Introductory Course 81

if A == B, ...
This is valid MATLAB code, and does what you expect when A and B are scalars. But when
A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the
result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and
B are not the same size, then A == B is an error.)

>>A = magic(4);
>>B = A;
>>B(1,1) = 0;
>>A == B
ans =
0111
1111
1111
1111

The proper way to check for equality between two variables is to use the isequal function:
if isequal(A, B), ...
isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix,
as the expression to be evaluated by the if function.
Using the A and B matrices from above, you get
>> isequal(A, B)
ans =
0

Here is another example to emphasize this point. If A and B are scalars, the following
program will never reach the "unexpected situation". But for most pairs of matrices, including
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end

our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or
A == B is true for all elements and so the else clause is executed:
Several functions are helpful for reducing the results of matrix comparisons to scalar
conditions for use with if, including ‘isequal’, ‘isempty’, ‘all’, ‘any’.

The most basic construct is:


if <condition>,
<program>
end
Here the condition is a logical expression that will evaluate to either true or false (i.e., with
values 1 or 0). When the logical expression evaluates to 0, the program control moves on to
the next program construction. You should keep in mind that MATLAB regards A==B and
A<=B as functions with values 0 or 1.

mat1-06-flow-control
81
G.A. El-Sheikh MATLAB: Introductory Course 82

Example-6.3.1:
>> a = 1;
>> b = 2;
>> if a < b,
c = 3;
end;
>> c
c =
3
>>

Example,
if rem(a,2) == 0
disp('a is even')
b = a/2;
end

If the logical expression evaluates to a nonscalar value, all the elements of the argument must
be nonzero. For example, assume X is a matrix. Then the statement
if X
statements
end
is equivalent to
if all(X(:))
statements
end

6.3.2 If-else-end Construct


Frequently, this construction is elaborated with
if <condition1>,
<program1>
else
<program2>
end
In this case if condition is 0, then program2 is executed.

if Statements and Empty Arrays


An if condition that reduces to an empty array represents a false condition. That is,
if A
S1
else
S0
end
will execute statement S0 when A is an empty array.

6.3.3 If-elseif-end Construct


Another variation is
if <condition1>,
<program1>

mat1-06-flow-control
82
G.A. El-Sheikh MATLAB: Introductory Course 83

elseif
<condition2>,
<program2>
end
Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is
not 0, then program2 is executed, and otherwise control is passed on to the next construction.

MATLAB's algorithm for generating a magic square of order n involves three different cases:
when n is odd, when n is even but not divisible by 4, or when n is divisible by 4. This is
described by
if rem(n,2) ~= 0
M = odd_magic(n)
elseif rem(n,4) ~= 0
M = single_even_magic(n)
else
M = double_even_magic(n)
end
In this example, the three cases are mutually exclusive, but if they weren't, the first true
condition would be executed.

The else and elseif statements further conditionalize the if statement:


 The else statement has no logical condition. The statements associated with it execute if
the preceding if (and possibly elseif condition) is false (0).
 The elseif statement has a logical condition that it evaluates if the preceding if (and
possibly elseif condition) is false (0). The statements associated with it execute if its
logical condition is true (1). You can have multiple elseifs within an if block.

if n < 0 % If n negative, display error message.


disp('Input must be positive');
elseif rem(n,2) == 0 % If n positive and even, divide by 2.
A = n/2;
else
A = (n+1)/2; %If n positive and odd, increment and divide.
end

6.3.4 Switch and Case


The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching
case is executed. There must always be an end to match the switch.
The syntax is as follows;
switch <condition or expression>
case <condition>
<statements>;

case <condition>

otherwise
<statements>;
end

mat1-06-flow-control
83
G.A. El-Sheikh MATLAB: Introductory Course 84

An example is shown below;

n=5
switch rem(n,2) % to find remainder of any number ‘n’
case 0
disp(‘Even Number’) % if remainder is zero
case 1
disp(‘Odd Number’) % if remainder is one
end

Unlike the C language switch statement, MATLAB switch does not fall through. If the first
case statement is true, the other case statements do not execute. So, break statements are not
required.

Examples:
It checks the variable input_num for certain values. If input_num is -1, 0, or 1, the
case statements display the value on screen as text. If input_num is none of these values,
execution drops to the otherwise statement and the code displays the text 'other
value'.
switch input_num
case -1
disp('negative one');
case 0
disp('zero');
case 1
disp('positive one');
otherwise
disp('other value');
end

switch can handle multiple conditions in a single case statement by enclosing the case
expression in a cell array.
switch var
case 1
disp('1')
case {2,3,4}
disp('2 or 3 or 4')
case 5
disp('5')
otherwise
disp('something else')
end

6.4 Looping Constructs


This section covers those MATLAB functions (For, while, break and continue) that provide
control over program loops.

6.4.1 For Loops

mat1-06-flow-control
84
G.A. El-Sheikh MATLAB: Introductory Course 85

The ‘for’ loop, is used to repeat a group of statements for a fixed, predetermined number of times.
A matching ‘end’ delineates the statements. The syntax is as follows:
for <index> = <starting number>:<step or increment>:<ending number>
<statements>;
End
The default increment is 1. You can specify any increment, including a negative one. For
positive indices, execution terminates when the value of the index exceeds the end value; for
negative increments, it terminates when the index is less than the end value.

A for loop is a construction of the form;


for i=1:n, <program>, end
Here we will repeat program once for each index value i.

For example, this loop executes five times;


for i = 2:6
x(i) = 2*x(i-1);
end

A for loop is a construction of the form;


for i= 1 : n,
<program>,
end

The program will repeat <program> once for each index value i = 1, 2 .... n. Here are some
examples of MATLAB's for loop capabilities:

for n = 1:4
r(n) = n*n; % square of a number
end
r

for n = 3:32
r(n) = rank(magic(n));
end
r

The semicolon terminating the inner statement suppresses repeated printing, and the r after the
loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested:
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end

Example-6.4.1: The basic for loop


>> for i = 1 : 5,
c = 2*i
end

mat1-06-flow-control
85
G.A. El-Sheikh MATLAB: Introductory Course 86

c =
2
..... lines of output removed ...
c =
10
>>
computes and prints "c = 2*i" for i = 1, 2, ... 5.

Example-6.4.2: For looping constructs may be nested. Here is an example of creating a


matrices contents inside a nested for loop:
>> for i=1:10,
for j=1:10,
A(i,j) = i/j;
end
end
>> A

There are actually two loops here, with one nested inside the other; they define
A(1,1), A(1,2), A(1,3)... A(1,10), A(2,1), ... A(10,10)
in that order.

Using Arrays as Indices


The index of a for loop can be an array. For example, consider an m-by-n array A. The
statement;
for i = A
statements
end
sets i equal to the vector A(:,k). For the first loop iteration, k is equal to 1; for the second
k is equal to 2, and so on until k equals n. That is, the loop iterates for a number of times
equal to the number of columns in A. For each iteration, i is a vector containing one of the
columns of A.

You can often speed up the execution of MATLAB code by replacing for and while loops
with vectorized code.
Example-6.4.3: MATLAB will allow you to put any vector in place of the vector 1:n in
this construction. Thus the construction
>> for i = [2,4,5,6,10],
<program>,
end
is perfectly legitimate. In this case program will execute 5 times and the values for the
variable i during execution are successively, 2,4,5,6,10.

Example-6.4.4
The MATLAB developers went one step further. If you can put a vector in, why not put a
matrix in? So, for example,
>> for i=magic(7),
<program>,
end
is also legal. Now the program will execute 7 (=number of columns) times, and the values of i
used in program will be successively the columns of magic(7).

mat1-06-flow-control
86
G.A. El-Sheikh MATLAB: Introductory Course 87

6.4.2 While Loops


The ‘while’ loop, repeats a group of statements indefinite number of times under control of a
logical condition. So a while loop executes at least once before it checks the condition to stop
the execution of statements. A matching ‘end’ delineates the statements. The syntax of the
‘while’ loop is as follows:
while <condition>
<statements>;
end

A while loop is a construction of the form


while <condition>,
<program1>,
end
where condition is a MATLAB function, as with the branching construction. The program
program1 will execute successively as long as the value of condition is not 0. While loops
carry an implicit danger in that there is no guarantee in general that you will exit a while loop.

Here is a sample program using a while loop.


function l=twolog(n)

% l=twolog(n). l is the floor of the base 2


% logarithm of n.
l=0;
m=2;
while m<=n
l=l+1;
m=2*m;
end

Example-6.4.5
Here is a complete program, illustrating while, if, else, and end that uses interval bisection to
find a zero of a polynomial:

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x

The result is a root of the polynomial x3 - 2x - 5, namely x = 2.0945. The cautions involving
matrix comparisons that are discussed in the section on the if statement also apply to the while
statement.

mat1-06-flow-control
87
G.A. El-Sheikh MATLAB: Introductory Course 88

The while loop executes a statement or group of statements repeatedly as long as the
controlling expression is true (1). Its syntax is
while expression
statements
end
If the expression evaluates to a matrix, all its elements must be 1 for execution to continue.
To reduce a matrix to a scalar value, use the all and any functions.

For example, this while loop finds the first integer n for which n! (n factorial) is a 100-
digit number.
n = 1;
while prod(1:n) < 1e100
n = n + 1;
end
Exit a while loop at any time using the break statement.

Remarks
A relation between matrices is interpreted by while and if to be true if each entry of the
relation matrix is nonzero. Hence, if you wish to execute statement when matrices A and B are
equal you could type;
if A == B
statement
end
but if you wish to execute statement when A and B are not equal, you would type
if any(any(A ~ B))
( statement )
end
or, more simply,
if A == B else
{ statement }
end

while Statements and Empty Arrays


A while condition that reduces to an empty array represents a false condition. That is,
while A, S1, end
never executes statement S1 when A is an empty array.

6.4.3 Break
The break statement lets you exit early from a ‘for’ loop or ‘while’ loop. In nested loops,
break exits from the innermost loop only. Above is an improvement on the example from the
previous section. Why is this use of break a good idea?

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;

mat1-06-flow-control
88
G.A. El-Sheikh MATLAB: Introductory Course 89

else
b = x; fb = fx;
end
end
x

When a break statement is encountered, execution continues with the next statement outside
of the loop. In nested loops, break exits from the innermost loop only. The example below
shows a while loop that reads the contents of the file fft.m into a MATLAB character
array. A break statement is used to exit the while loop when the first empty line is
encountered. The resulting character array contains the M-file help for the fft program.
fid = fopen('fft.m','r');
s = '';
while ~feof(fid)
line = fgetl(fid);
if isempty(line)
break
end
s = strvcat(s,line);
end
disp(s)

6.4.4 Continue
The continue statement passes control to the next iteration of the for-loop or while-loop in
which it appears, skipping any remaining statements in the body of the loop. The same holds
true for continue statements in nested loops. That is, execution continues at the beginning of
the loop in which the continue statement was encountered.

The example below shows a continue loop that counts the lines of code in the file,
magic.m, skipping all blank lines and comments. A continue statement is used to advance
to the next line in magic.m without incrementing the count whenever a blank line or comment
line is encountered.
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));

Some Notes:
A relation between matrices is interpreted by while and if to be true if each entry of the
relation matrix is nonzero. Hence, if you wish to execute statement when matrices A and B are
equal you could type
if A == B
statement

mat1-06-flow-control
89
G.A. El-Sheikh MATLAB: Introductory Course 90

end
but if you wish to execute statement when A and B are not equal, you would type
if any(any(A ~ B))
( statement )
end
or, more simply,
if A == B else
{ statement }
End

6.4.5 try ... catch


The general form of a try ... catch statement sequence is
try,
statement,
...,
statement,
catch,
statement,
...,
statement,
end
In this sequence the statements between try and catch are executed until an error occurs.
The statements between catch and end are then executed. Use lasterr to see the cause
of the error. If an error occurs between catch and end, MATLAB terminates execution
unless another try ... catch sequence has been established.

%*********************************************************
%*** try01.m ***
%*********************************************************
clc
clear
close all

% try and catch blocks allow you to override the


% default error behavior for a set of program statements.
% If any statement in a try block generates an error,
% program control goes immediately to the catch block,
% which contains your error handling statements.

% exception is an optional MException object input to


% the catch block that allows you to identify the error.

% Both try and catch blocks can contain nested try/catch statements.
% For Example; Provide more information about a dimension mismatch error:

A = rand(3);
B = ones(5);

try
C = [A; B];
catch err

% Give more information for mismatch.

mat1-06-flow-control
90
G.A. El-Sheikh MATLAB: Introductory Course 91

if (strcmp(err.identifier,'MATLAB:catenate:dimensionMismatch'))

msg = ['Dimension mismatch occurred: First argument has ', ...


num2str(size(A,2)), ' columns while second has ', ...
num2str(size(B,2)), ' columns.'];
error('MATLAB:myCode:dimensions', msg);

% Display any other errors as usual.


else
rethrow(err);
end

end % end try/catch

Output:
Error using try01 (line 30)
Dimension mismatch occurred: First argument has 3 columns while second has 5 columns.

6.4.6 return
return terminates the current sequence of commands and returns control to the invoking
function or to the keyboard. return is also used to terminate keyboard mode. A called
function normally transfers control to the function that invoked it when it reaches the end of
the function. return may be inserted within the called function to force an early termination
and to transfer control to the invoking function.

6.4.7 Recursion
Recursion is a devious construction which allows a function to call itself. Here is a simple
example of recursion
function y=twoexp(n)

% y=twoexp(n). This is a recursive program for computing


% y=2^n. The program halts only if n is a nonnegative integer.

if n==0, y=1;
else y=2*twoexp(n-1);
end
The program has a branching construction built in. Many recursive programs do. The condition n==0
is the base of the recursion. This is the only way to get the program to stop calling itself. The "else"
part is the recursion. Notice how the twoexp(n-1) occurs right there in the program which is defining
twoexp(n)! The secret is that it is calling a lower value, n-1, and it will continue to do so until it gets
down to n=0. A successful recursion is calling a lower value.

There are several dangers using recursion. The first is that, like while loops, it is possible for the
function to call itself forever and never return an answer. The second is that recursion can lead to
redundant calculations which, though they may terminate, can be time consuming. The third danger is
that while a recursive program is running it needs extra space to accomodate the overhead of the
recursion. In numerical calculations on very large systems of equations memory space is frequently at
a premium, and it should not be wasted on program overhead. With all of these bad possibilities why
use recursion? It is not always bad; only in the hands of an inexperienced user. Recursive programs
can be easier to write and read than nonrecursive programs. Some of the future projects illustrate good
and poor uses of recursion.

mat1-06-flow-control
91
G.A. El-Sheikh MATLAB: Introductory Course 92

6.5 Exercises-06: Flow Control


1- Use the MATLAB to generate the first 100 terms in the sequence P(n) defined recursively
by,
P(n  1)  a * P(n ) * (1  P(n )) ; with a=2.9 and P(1)=0.5.
Then plot the obtained sequence.

2- Using the MATLAB M-file Function capability;

a) Write a MATLAB M-file function to obtain numerical values of y(t). The function must
take y(0), ζ, ωn, t and  as function inputs and y(t) as output argument. The
mathematical expression is
y0
y( t )  e  n t sin( n 1   2 * t  )
1 
b) Write a second script m-file to obtain the plot for y(t) for 0<t<10 with an increment of
0.1, by considering the following two cases;
 Case 1: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 3/(2√2) and  = 0;
 Case 2: y0 = 0.15 m, ωn = √2 rad/sec, ζ = 1/(2√2) and  = 0;

Hint: When you write the function you would require element-by-element operator

3- Use the MATLAB ‘for’ or ‘while’ loop to convert degrees Fahrenheit (T f) to degrees
Celsius using the following equation;
9
Tf  * Tc  32
5
Use any starting temperature, increment and ending temperature (example: starting
temperature=0, increment=10, ending temperature = 200).

4- Any integer is input by the user; write a program to find out whether it is an odd number
or even number.
5- Find the absolute value of a number entered by the user.
6- Write a program to calculate the total expenses. Quantity and price per item are input by
the user and discount of 10% is offered if the expense is more than 5000.
7- Write a program to determine whether the seller has made profit or incurred loss. Also
determine how much profit he made or loss he incurred. Cost price and selling price of
an item is input by the user.
8-  If the ages of Ali, Mahmoud and Israa are input by the user, write a program to
determine the youngest of the three.
 If the ages of persons are input by the user, write a program to determine the youngest
of them.
9- Write a program to check whether a triangle is valid or not, when the three angles of the
triangle are entered by the user. A triangle is valid if the sum of all the three angles is
equal to 180 degrees.
10- Any year is input by the user. Write a program to determine whether the year is a leap
year or not.

mat1-06-flow-control
92
G.A. El-Sheikh MATLAB: Introductory Course 93

11- In a company an employee is paid as follows:


If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary
and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500,
then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input
by the user write a program to find his gross salary.
12- Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for upto 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
13- Write a program to find the roots of and quadratic equation of type (ax2+bx+c), where a
does not equal to zero.
14- The marks obtained by a student in 5 different subjects are input by the user. The
student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 – Fail
Write a program to calculate the division obtained by the student.
15- Any character is entered by the user; write a program to determine whether the character
entered is a capital letter, a small case letter, a digit or a special symbol. The following
table shows the range of ASCII values for various characters.
Characters ASCII Values
A–Z 65 – 90
a–z 97 – 122
0–9 48 – 57
special symbols 0 - 47, 58 - 64, 91 - 96, 123 – 127

16- Write a program to print number from 1 to 10.


17- Write a program to calculate the sum of first 10 natural number.
18- Write a program to find the factorial value of any number entered through the keyboard.
19- Two numbers are entered through the keyboard. Write a program to find the value of
one number raised to the power of another.
20- Write a program to reverse any given integer number.
21- Write a program to sum of digits of given integer number.
22- Write a program to check given number is prime or not.
23- Write a program to calculate HCF of Two given number.
24- Write a program to enter the numbers till the user wants and at the end it should display
the count of positive, negative and zeros entered.
25- Write a program to enter the numbers till the user wants and at the end it should display
the maximum and minimum number entered.
26- Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes
of each digit of the number is equal to the number itself, then the number is called an
Armstrong number.
For example 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

mat1-06-flow-control
93
G.A. El-Sheikh MATLAB: Introductory Course 94

27- Write a program to print Fibonacci series of n terms where n is input by user:
0 1 1 2 3 5 8 13 24 .....; it is given by the recursive form,
1  1  5   1  5  
n n

Fn  Fn 1  Fn 2 or Fn      
5  2   2  
 
28- Write a program to calculate the sum of following series where n is input by user; 1 +
1/2 + 1/3 + 1/4 + 1/5 +…………1/n
29- Compute the natural logarithm of 2, by adding up to n terms in the series; 1 - 1/2 + 1/3 -
1/4 + 1/5 -... 1/n, where n is a positive integer and input by user.
30- Write a program to display the following:
i) ********** ii) * iii) *
********** ** **
********** *** ***
********** **** ****
***** *****
iv) * v) 1 vi) 1
*** 222 212
***** 33333 32123
******* 4444444 4321234
********* 555555555 543212345

31- Write a program to compute sinx for given x. The user should supply x and a positive
integer n. We compute the sine of x using the series and the computation should use all
terms in the series up through the term involving xn; sin x = x - x3/3! + x5/5! - x7/7! + x9/9!
........
32- Write a program to compute the cosine of x. The user should supply x and a positive integer
n. We compute the cosine of x using the series and the computation should use all terms in
the series up through the term involving xn; cos x = 1 - x2/2! + x4/4! - x6/6! ....

33- Displaying the results in a good format, design a MATLAB program to,
 Read a set of measurements and stops for -ve entry,
 find the sum and Average the measurements, and
 Display the results.

mat1-06-flow-control
94
G.A. El-Sheikh MATLAB: Introductory Course 95

7- Character Arrays (Strings)


7.1 General
This chapter explains MATLAB's support for string data. It describes the two ways that
MATLAB represents strings:
 Character Arrays
 Cell Arrays of Strings
It also describes the operations that you can perform on string data under the following topics:
 String Comparisons
 Searching and Replacing
 String/Numeric Conversion

This table shows the string functions, which are located in the directory named strfun in the
MATLAB Toolbox;
Category Function Description
General blanks String of blanks
cellstr Create cell array of strings from character array
char Create character array (string)
deblank Remove trailing blanks
eval Execute string with MATLAB expression
String Tests iscellstr True for cell array of strings
ischar True for character array
isletter True for letters of alphabet.
isspace True for whitespace characters.
String Operations findstr Find one string within another
lower Convert string to lowercase
strcat Concatenate strings
strcmp Compare strings
strcmpi Compare strings, ignoring case
strjust Justify string
strmatch Find matches for string
strncmp Compare first N characters of strings
strncmpi Compare first N characters, ignoring case
strrep Replace string with another
strtok Find token in string
strvcat Concatenate strings vertically
upper Convert string to uppercase

mat1-07-string
95
G.A. El-Sheikh MATLAB: Introductory Course 96

String to Number Conversion double Convert string to numeric codes


int2str Convert integer to string
mat2str Convert matrix to eval'able string
num2str Convert number to string
sprintf Write formatted data to string
str2double Convert string to double-precision value
str2mat Form character matrix from strings
str2num Convert string to number
sscanf Read string under format control
Base Number Conversion base2dec Convert base B string to decimal integer
bin2dec Convert binary string to decimal integer
dec2base Convert decimal integer to base B string
dec2bin Convert decimal integer to binary string
dec2hex Convert decimal integer to hexadecimal string
hex2dec Convert hexadecimal string to decimal integer
hex2num Convert IEEE hexadecimal to double-precision
number

7.2 Character Arrays


In MATLAB, the term string refers to an array of characters. MATLAB represents each
character internally as its corresponding numeric value. Unless you want to access these
values, however, you can simply work with the characters as they display on screen.

7.2.1 Creating Character Arrays


Specify character data by placing characters inside a pair of single quotes. For example, this
line creates a 1-by-13 character array called name.
>> name = 'Ali M. Saed';
In the workspace, the output of whos shows
Name Size Bytes Class

name 1x11 22 char array


You can see that a character uses two bytes of storage internally.

The class and ischar functions show name's identity as a character array;
>> class(name)
ans =
char

>> ischar(name)
ans =
1

mat1-07-string
96
G.A. El-Sheikh MATLAB: Introductory Course 97

>> X1=25;
>> ischar(X1)
ans =
0
You can also join two or more character arrays together to create a new character array. Use
either the string concatenation function, strcat, or the MATLAB concatenation operator, [], to
do this.
>> name = ' Ali M. Saed ';
>> title = ' Network Developer';
>> strcat(name,',',title)

ans =
Ali M. Saed, Network Developer
You can also concatenate strings vertically with strvcat.

str2num: Converts string matrix to numeric array. X1 = str2num(S1) converts a character


array representation of a matrix of numbers to a numeric matrix.

For example,
>> S1 = ['1 2' ; '3 4'];
>> str2num(S1) => [1 2;3 4]
ans =
1 2
3 4

7.2.2 Creating Two-Dimensional Character Arrays


When creating a two-dimensional character array, be sure that each row has the same length.
For example, this line is legal because both input rows have exactly 13 characters.
>> name = ['Ali M. Saed' ; 'Web Developer']
name =
Ali M. Saed
Web Developer

When creating character arrays from strings of different lengths, you can pad the shorter
strings with blanks to force rows of equal length.
>> name = [' Ali M. Saed '; 'Senior Developer'];

A simpler way to create string arrays is to use the char function.


char automatically pads all strings to the length of the longest input string. In this example,
char pads the 13-character input string ' Ali M. Saed ' with three trailing blanks so that it
will be as long as the second string.
>> name = char(' Ali M. Saed','Senior Developer')
name =
Ali M. Saed
Senior Developer

When extracting strings from an array, use the deblank function to remove any trailing
blanks;

mat1-07-string
97
G.A. El-Sheikh MATLAB: Introductory Course 98

>> trimname = deblank(name(1,:)) >> size(trimname)


trimname = ans =
Ali M. Saed 1 14

7.2.3 Converting Characters to Numeric Values


Character arrays store each character as a 16-bit numeric value. Use the double function to
convert strings to their numeric values, and char to revert to character representation;
>> name = double(name) >> name = char(name)
name = name =
Columns 1 through 10 Ali M. Saed
32 65 108 105 32 32 32 77 46 32 Senior Developer
83 101 110 105 111 114 32 68 101 118
Columns 11 through 16
83 97 101 100 32 32
101 108 111 112 101 114

Use str2num to convert a character array to the numeric value represented by that string;
>> str = '37.294e-1';
>> val = str2num(str)
val =
3.7294

7.3 Cell Arrays of Strings


It's often convenient to store groups of strings in cell arrays instead of standard character
arrays. This prevents you from having to pad strings with blanks to create character arrays
with rows of equal length. A set of functions enables you to work with cell arrays of strings:
 You can convert between standard character arrays and cell arrays of strings.
 You can apply string comparison operations to cell arrays of strings.

7.3.1 Converting to a Cell Array of Strings


The cellstr function converts a character array into a cell array of strings. Consider the
character array
>> data = ['Mohamed Ali';'Development ';'We Inc.'];

Each row of the matrix is padded so that all have equal length (in this case, 13 characters).
Now use cellstr to create a column vector of cells, each cell containing one of the strings
from the data array.
>> celldata = cellstr(data)

celldata =
' Mohamed Ali'
'Development'
'We Inc.'

Note that the cellstr function strips off the blanks that pad the rows of the input string
matrix.
>> length(celldata{3})

ans =
7

mat1-07-string
98
G.A. El-Sheikh MATLAB: Introductory Course 99

The iscellstr function determines if the input argument is a cell array of strings. It returns a
logical true (1) in the case of celldata.
>> iscellstr(celldata)

ans =
1
Use char to convert back to a standard padded character array.
>> strings = char(celldata)

strings =
Mohamed Ali
Development
We Inc.

7.3.2 String/Numeric Conversions


MATLAB's string/numeric conversion functions change numeric values into character strings.
You can store numeric values as digit-by-digit string representations, or convert a value into a
hexadecimal or binary string. Consider a the scalar
x = 5317;

By default, MATLAB stores the number x as a 1-by-1 double array containing the value
5317. The int2str (integer to string) function breaks this scalar into a 1-by-4 vector
containing the string '5317'.
>> y = int2str(x);
>> size(y)

ans =
1 4
A related function, num2str, provides more control over the format of the output string. An
optional second argument sets the number of digits in the output string, or specifies an actual
format.
>> p = num2str(pi,9)

p =
3.14159265
Both int2str and num2str are handy for labeling plots.

For example, the following lines use num2str to prepare automated labels for the x-axis of a
plot.
function plotlabel(x,y)
plot(x,y)
str1 = num2str(min(x));
str2 = num2str(max(x));
out = ['Value of f from ' str1 ' to ' str2];
xlabel(out);

Another class of numeric/string conversion functions changes numeric values into strings
representing a decimal value in another base, such as binary or hexadecimal representation.
For example, the dec2hex function converts a decimal value into the corresponding
hexadecimal string.

mat1-07-string
99
G.A. El-Sheikh MATLAB: Introductory Course 100

>> dec_num = 4035;


>> hex_num = dec2hex(dec_num)

hex_num =
FC3
See the strfun directory for a complete listing of string conversion functions.

The str2double function converts a cell array of strings to the double-precision values
represented by the strings.
>> c = {'37.294e-1'; '-58.375'; '13.796'};
>> str2double(c)

ans =
3.7294
-58.3750
13.7960

Array/String Conversion
The MATLAB function mat2str changes an array to a string that MATLAB can evaluate.
This string is useful input for a function such as eval, which evaluates input strings just as if
they were typed at the MATLAB command line.
Create a 2-by-3 array A.
>> A = [1 2 3; 4 5 6]

A =
1 2 3
4 5 6
mat2str returns a string that contains the text you would enter to create A at the command
line.
>> B = mat2str(A)

B =
[1 2 3; 4 5 6]

7.4 String Comparisons


There are several ways to compare strings and substrings:
 You can compare two strings, or parts of two strings, for equality.
 You can compare individual characters in two strings for equality.
 You can categorize every element within a string, determining whether each element
is a character or whitespace.
These functions work for both character arrays and cell arrays of strings.

7.4.1 Comparing Strings for Equality


There are four functions that determine if two input strings are identical:
 strcmp determines if two strings are identical.
 strncmp determines if the first n characters of two strings are identical.
 strcmpi and strncmpi are the same as strcmp and strncmp, except that they ignore
case.

mat1-07-string
100
G.A. El-Sheikh MATLAB: Introductory Course 101

Consider the two strings


>> str1 = 'hello';
>> str2 = 'help';
Strings str1 and str2 are not identical, so invoking strcmp returns 0 (false). For
example,
>> C = strcmp(str1,str2)

C =
0
Note: For C programmers, this is an important difference between MATLAB's strcmp and C's
strcmp(), which returns 0 if the two strings are the same.

The first three characters of str1 and str2 are identical, so invoking strncmp with any value
up to 3 returns 1.
>> C = strncmp(str1,str2,2) % Compares first-two characters
C =
1
These functions work cell-by-cell on a cell array of strings. Consider the two cell arrays of
strings;
>> A = {'pizza';'chips';'candy'};
>> B = {'pizza';'chocolate';'pretzels'};

Now apply the string comparison functions.


>> strcmp(A,B)

ans =
1
0
0

>> strncmp(A,B,1)

ans =
1
1
0

7.4.2 Comparing for Equality using Operators


You can use MATLAB relational operators on character arrays, as long as the arrays you are
comparing have equal dimensions, or one is a scalar. For example, you can use the equality
operator (==) to determine which characters in two strings match.
>> A = 'fate';
>> B = 'cake';
>> A == B

ans =
0 1 0 1
All of the relational operators (>, >=, <, <=, ==, !=) compare the values of corresponding
characters.

mat1-07-string
101
G.A. El-Sheikh MATLAB: Introductory Course 102

7.4.3 Categorizing Characters within a String


There are two functions for categorizing characters inside a string:
 isletter determines if a character is a letter
 isspace determines if a character is whitespace (blank, tab, or new line)
For example, create a string named mystring.
mystring = 'Room 401';
isletter examines each character in the string, producing an output vector of the same
length as mystring.
>> A = isletter(mystring)

A =
1 1 1 1 0 0 0 0
The first four elements in A are 1 (true) because the first four characters of mystring are
letters.

7.5 String Searching and Replacing


MATLAB provides several functions for searching and replacing characters in a string.
Consider a string named label.
>> label = 'Sample 1, 10/28/95';

The strrep function performs the standard search-and-replace operation. Use strrep to
change the date from '10/28' to '10/30'.
>> newlabel = strrep(label,'28','30')

newlabel =

Sample 1, 10/30/95

findstr returns the starting position of a substring within a longer string. To find all
occurrences of the string 'amp' inside label
>> position = findstr('amp',label)

position =
2
The position within label where the only occurrence of 'amp' begins is the second character.

The strtok function returns the characters before the first occurrence of a delimiting
character in an input string. The default delimiting characters are the set of whitespace
characters. You can use the strtok function to parse a sentence into words;
For example,
function all_words = words(input_string)
remainder = input_string;
all_words = '';

while (any(remainder))
[chopped,remainder] = strtok(remainder);
all_words = strvcat(all_words,chopped);
end

mat1-07-string
102
G.A. El-Sheikh MATLAB: Introductory Course 103

The strmatch function looks through the rows of a character array or cell array of strings to
find strings that begin with a given series of characters. It returns the indices of the rows that
begin with these characters.
>> maxstrings = strvcat('max','minimax','maximum')

maxstrings =

max
minimax
maximum

>> strmatch('max',maxstrings)

ans =
1
3

7.6 String Evaluation


String evaluation adds power and flexibility to the MATLAB language, letting you perform
operations like executing user-supplied strings and constructing executable strings through
concatenation of strings stored in variables.

eval
The eval function evaluates a string that contains a MATLAB expression, statement, or
function call. In its simplest form, the eval syntax is
>> eval('string') or >> eval('char')

Example-7.6.1:
This code uses eval on an expression to generate a Hilbert matrix of order n.
%*****************************************
% *** string01.m ***
%*****************************************
%*** String evaluation and processing ***
%*****************************************
clc
clear
close all

t1 = '1/(i + j-1)';
n1 = 5;

for i = 1:n1
for j = 1:n1
a(i,j) = eval(t1);
end
end
a

Here's an example that uses eval on a statement.

mat1-07-string
103
G.A. El-Sheikh MATLAB: Introductory Course 104

>> eval('t = clock');

Constructing Strings for Evaluation


You can concatenate strings to create a complete expression for input to eval. This code
shows how eval can create 10 variables named P1, P2, ...P10, and set each of them to a
different value.
for i=1:10
eval(['P',int2str(i),'= i.^2'])
end

feval
The feval function differs from eval in that it executes a function rather than a MATLAB
expression. The function to be executed is specified in the first argument by either a function
handle or a string containing the function name. You can use feval and the input function to
choose one of several tasks defined by M-files. This example uses function handles for the
sin, cos, and log functions.
%*****************************************
% *** string02.m ***
%*****************************************
%*** String evaluation and processing ***
%*****************************************
clc
clear
close all

fun1 = [@sin; @cos; @log];


k1 = input(' Choose function number: ');
x1 = input(' Enter value: ');
feval(fun1(k1),x1)

Note: Use feval rather than eval whenever possible. M-files that use feval execute faster and
can be compiled with the MATLAB Compiler.

7.7 Exercises-07
1- Using the MATLAB, design a program to carry on the following assignments;
 find the length of a string.
 display a string from backward.
 count number of words in a string.
 concatenate one string contents to another.
 compare two strings whether they are exact equal or not.
 check a string whether it is palindrome or not.
 find a substring within a string; If found display its starting position.
 reverse a string.
 convert a string into lowercase.
 convert a string into uppercase.

2- Using MATLAB, write a program to manipulate strings;


 Interacts with the user to enter strings

mat1-07-string
104
G.A. El-Sheikh MATLAB: Introductory Course 105

 Finds the
‒ Length of string
‒ Number of words
‒ Reverse a String
‒ Concatenate Strings
 Display the results in a good format according to required action.

3- Using MATLAB programming, design a program to be used with the exams-control for
finding students grades in your Institute such that it accepts the following inputs,
 Student name
 Course name
 Mark for each student and course
 Grade for each student and course
Then, it displays the list of students with courses and grades. In addition, it can show the
number of students in each grade with percentages or any other information. Consider the
given table to show you the grading system,
Score Grade
>=85 Excellent
75% - <85% V.Good
65% - <75% Good
50% - <65% Sufficient
<50% Fail
The output data has the form,
No Student Name Course Name Mark Grade

mat1-07-string
105
G.A. El-Sheikh MATLAB: Introductory Course 106

8- Graphics
Two- and three-dimensional MATLAB graphs can be given titles, have their axes labeled,
and have text placed within the graph. The basic functions are:
Function Description
plot(x,y) plots y vs x
plot(x,y1,x,y2,x,y3) plots y1, y2 and y3 vs x on the same graph
xlabel('x axis label') labels x axis
ylabel('y axis label') labels y axis
title ('title of plot') puts a title on the plot
gtext('text') activates the use of the mouse to position a
crosshair on the graph, at which point the
'text' will be placed when any key is pressed.
ezplot easy plotting of functions

MATLAB graphics windows will contain one plot by default. The command "subplot" can be
used to partition the screen so that up to four plots can be viewed simultaneously. For more
information, type
>> help subplot

8.1 Two-Dimensional Plots


The plot command creates linear x-y plots; if x and y are vectors of the same length, the
command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x
versus the elements of y.

Example-8.1:
Let's draw the graph of the sine function over the interval -4 to 4 with the following
commands:
>> x = -4:.01:4; y = sin(x); plot(x,y)
>> grid
>> xlabel('x')
>> ylabel('sin(x)')

The vector x is a partition of


the domain with meshsize
0.01 while y is a vector
giving the values of sine at
the nodes of this partition
(recall that sin operates
entrywise). The result is
shown in Fig. 8.1.

Fig. 8.1: sin(x) versus x from -4 to 4

mat1-08-graphics
106
G.A. El-Sheikh MATLAB: Introductory Course 107

Example-8.2:
Plots of parametrically defined curves can also be made. For example,
>> t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)

Example-8.3:
Two ways to make multiple plots on a single graph are illustrated by
>> x = 0:.01:2*pi;y1=sin(x);y2=sin(2*x);
>> y3 = sin(4*x);plot(x,y1,x,y2,x,y3)
and by forming a matrix Y containing the functional values as columns
>> x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)
Another way is with hold. The command hold freezes the current graphics screen so that
subsequent plots are superimposed on it. Entering hold again releases the ``hold.''

Example-8.4:
One can override the default linetypes and pointtypes. For example, the command sequence
>> x = 0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);
>> plot(x,y1,'--',x,y2,':',x,y3,'+')
>> grid
>> title ('Dashed line and dotted line graph')
renders a dashed line and dotted line for the first two graphs while for the third the symbol is
placed at each node. See Figure 3.

Figure 3: Overriding default line- and point- types

The line- and mark-types are


=============================================================
Linetypes : solid (-), dashed (-). dotted (:), dashdot (-.)
Marktypes : point (.), plus (+), star (*, circle (o),
x-mark (x)
=============================================================
See (>> help plot) for line and mark colors.

mat1-08-graphics
107
G.A. El-Sheikh MATLAB: Introductory Course 108

8.2 Two-Dimensional Contour Plots


Functions of two variables may be plotted, as well, but some "setup" is required!
>> [x y] = meshgrid(-3:.1:3, -3:.1:3);
>> z = x.^2 - y.^2;
>> mesh(x,y,z)
>> surf(x,y,z)
>> contour(z)
Notice how in the second command, the dot
operator is inserted to computer the difference
of
z(x,y) = x^2 - y^2
at the matrix element level.
The result of these commands is shown in
Figure 4.

Fig. 4: Contour Map of z = x^2 - y^2


Some commands:
plot(x,y) creates a Cartesian plot of the vectors x & y
plot(y) creates a plot of y vs. the numerical values of the elements in the y-vector.
semilogx(x,y) plots log(x) vs y
semilogy(x,y) plots x vs log(y)
loglog(x,y) plots log(x) vs log(y)
grid creates a grid on the graphics plot
title('text') places a title at top of graphics plot
xlabel('text') writes 'text' beneath the x-axis of a plot
ylabel('text') writes 'text' beside the y-axis of a plot
text(x,y,'text') writes 'text' at the location (x,y)
text(x,y,'text','sc') writes 'text' at point x,y assuming lower left corner is (0,0) and upper
right corner is (1,1).
polar(theta,r) creates a polar plot of the vectors r & theta, where theta is in radians.
bar(x) creates a bar graph of the vector x. (Note also the command stairs(x).)
bar(x,y) creates a bar-graph of the elements of the vector y,
locating the bars according to the vector elements
of 'x'. (Note also the command stairs(x,y).)

mat1-08-graphics
108
G.A. El-Sheikh MATLAB: Introductory Course 109

8.3 Cartesian or X-Y Plots


One of 'matlab' most powerful features is the ability to create graphic plots. Here we introduce
the elementary ideas for simply presenting a graphic plot of two vectors. More complicated
and powerful ideas with graphics can be found in the 'matlab' documentation.

A Cartesian or orthogonal x,y plot is based on plotting the x,y data pairs from the specified
vectors. Clearly, the vectors x and y must have the same number of elements. Imagine that
you wish to plot the function ex for values of x from 0 to 2.

x = 0:.1:2;
y = exp(x);
plot(x,y)

NOTE: The use of selected functions such as exp() and


sin() will be used in these tutorials without explanation if
they take on an unambiguous meaning consistent with
past experience. Here it is observed that operating on a
matrix with these functions simply creates a matrix in
which the elements are based on applying the function to
each corresponding element of the argument.

Of course the symbols x,y are arbitrary. If we wanted to plot temperature on the ordinate and
time on the abscissa, and vectors for temperature and time were loaded in 'matlab', the
command would be
plot(time,temperature)

Notice that the command plot(x,y) opens a graphics window. If you now execute the
command 'grid', the graphics
window is redrawn. (Note you
move the cursor to the command
window before typing new
commands.) To avoid redrawing the
window, you may use the line
continuation ellipsis. Consider

plot(x,y),...
grid,...
title('Exponential Function'),...
xlabel('x'),...
ylabel('exp(x)'),
text(.6,.4,' y = exp(x)','sc')

Note that if you make a mistake in


typing a series of lines of code, such
as the above, the use of line
continuation can be frustrating. In a
future lesson, we will learn how to
create batch files (called '.m' files)
for executing a series of 'matlab' commands. This approach gives you better opportunity to
return to the command string and edit errors that have been created.

mat1-08-graphics
109
G.A. El-Sheikh MATLAB: Introductory Course 110

Having defined the vectors x and y, construct semilog and loglog plots using these or other
vectors you may wish to create. Note in particular what occurs when a Logarithmic scale is
selected for a vector that has negative or zero elements. Here, the vector x has a zero element
(x(1)=0). The logarithm of zero or any negative number is undefined and the x,y data pair for
which a zero or negative number occurs is discarded and a warning message provided.

Try the commands plot(x) and plot(y) to ensure you understand how they differ from
plot(x,y).

Notice that 'matlab' draws a straight line between the datapairs. If you desire to see a
relatively smooth curve drawn for a rapidly changing function, you must include a number of
data points. For example, consider the trigonometric function, sin(x1) (x1 is selected as the
argument here to distinguish it from the
vector 'x' that was defined earlier. )

Plot sin(x1) over the limits 0 <= x1 <= pi.


First define x1 with 5 elements,

x1 = 0 : pi/4 : pi
y1 = sin(x1)
plot(x1,y1)

Now, repeat this after defining a new vector for x1 and y1 with 21 elements. (Note the use of
the semicolon here to prevent the printing and scrolling on the monitor screen of a vector or
matrix with a large number of 1
elements!)
0.9

x1=0:0.05*pi:pi; 0.8

y1=sin(x1); 0.7
plot(x1,y1,'linewidth',3), grid on
0.6

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5

mat1-08-graphics
110
G.A. El-Sheikh MATLAB: Introductory Course 111

8.4 Polar Plots


Imaginary and Complex Data
When the arguments to plot are complex, the imaginary part is ignored except when plot is
given a single complex argument. For this special case, the command is a shortcut for a plot
of the real part versus the imaginary part. Therefore,
plot(Z)
where Z is a complex vector or matrix, is
equivalent to
plot(real(Z),imag(Z))

For example,
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')
axis equal
draws a 20-sided polygon with little circles at
the vertices. The command, axis equal, makes
the individual tick mark increments on the x-
and y-axes the same length, which makes this
plot more circular in appearance.

Polar plots are constructed much the same way as are Cartesian x-y plots; however, the
arguments are the angle 'theta' in radians measured CCW from the horizontal (positive-x)
axis, and the length of the radius vector extended from
the origin along this angle. Polar plots do not allow
the labeling of axes; however, notice that the scale for
the radius vector is presented along the vertical and
when the 'grid' command is used the angles-grid is
presented in 15-degree segments. The 'title' command
and the 'text' commands are functional with polar
plots.

angle = 0:.1*pi:3*pi;
radius = exp(angle/20);
polar(angle,radius),...
title('An Example Polar Plot'),...
grid

Note that the angles may exceed one revolution of


2*pi.
The MATLAB program (polygon08.m) is used to create these Figures.

mat1-08-graphics
111
G.A. El-Sheikh MATLAB: Introductory Course 112

8.5 Multiple Plots


More than a single graph can be presented on one graphic plot. One common way to
accomplish this is hold the graphics 1
window open with the 'hold' command
and execute a subsequent plotting 0.8
command. 0.6

0.4
x1=0:0.05*pi:pi;
y1=sin(x1); 0.2

plot(x1,y1,'b','linewidth',3) 0
hold
-0.2
y2=cos(x1);
plot(x1,y2,'r--','linewidth',3), grid on -0.4

-0.6
The "hold" command will remain active
-0.8
until you turn it off with the command
'hold off'. -1
0 0.5 1 1.5 2 2.5 3 3.5

You can create multiple graphs by using multiple arguments. In addition to the vectors x, y
created earlier, create the vectors a,b and plot both vector sets simultaneously as follows;
4

x1=0:0.05*pi:pi;
3.5
y1=sin(x1);
a = 1 :0.1 : 3; 3

b = 10*exp(-a); 2.5
plot(x1,y1,'b',a,b,'r--','linewidth',3), grid on
2

Multiple plots can be accomplished also by using 1.5


matrices rather than simple vectors in the argument.
If the arguments of the 'plot' command are 1
matrices, the COLUMNS of y are plotted on the 0.5
ordinate against the COLUMNS of x on the 0
abscissa. Note that x and y must be of the same 0 0.5 1 1.5 2 2.5 3 3.5

order! If y is a matrix and x is a vector, the rows or columns of y are plotted against the
elements of x. In this instance, the number of rows OR columns in the matrix must correspond
to the number of elements in 'x'. The matrix 'x' can be a row or a column vector!

Recall the row vectors 'x1' and 'y1' defined earlier. 10

Augment the row vector 'y2' to create the 2-row 9

matrix, y12; 8

7
x1=0:0.05*pi:pi; 6
y1=sin(x1);
5
y2 = 10*exp(-x1);
4
y12 = [y1;y2];
3
plot(x1,y12,'linewidth',3), grid on
2

0
0 0.5 1 1.5 2 2.5 3 3.5

mat1-08-graphics
112
G.A. El-Sheikh MATLAB: Introductory Course 113

8.6 Plotting Data Points with Declarations


Matlab connects a straight line between the data pairs described by the vectors used in the
'print' command. You may wish to present data points and omit any connecting lines between
these points. Data points can be described by a variety of characters ( . , + , * , o and x .) The
following command plots the x,y data as a "curve" of connected straight lines and in addition
places an 'o' character at each of the x1,y1 data pairs.

>> plot(x,y,x1,y1,'o')

Lines can be colored and they can be broken to make distinctions among more than one line.
Colored lines are effective on the color monitor and color printers or plotters. Colors are
useless on the common printers used on this network. Colors are denoted in 'matlab' by the
symbols r(red), g(green), b(blue), w(white) and i(invisible). The following command plots the
x,y data in red solid line and the r,s data in broken green line.

>> plot(x,y,'r',r,s,'--g')

Built-in axis modes;


 Axis square; makes the current axis look like a square box
 Axis tight; fits axes to data
 Axis equal; makes x and y scales the same
 Axis xy; puts the origin in the lower left corner (default for plots)
 Axis ij; puts the origin in the upper left corner (default for matrices/images)

8.7 Printing Graphic Plots


Executing the 'print' command will send the contents of the current graphics widow to the
local printer. You may wish to save in a graphics file, a plot you have created. To do so,
simply append to the 'print' command the name of the file. The command

>> print filename

will store the contents of the graphics window in the file titled 'filename.ps' in a format called
postscript. You need not include the .ps suffix, as matlab will do this. When you list the files
in your matlab directory, it is convenient to identify any graphics files by simply looking for
the files with the .ps suffix. If you desire to print one of these postscript files, you can
conveniently "drag and drop" the file from the file-manager window into the printer icon.

8.8 Three-Dimensional Graphics


Three dimensional mesh surface plots are drawn with the functions
Function Description
=====================================================================
mesh(z) Creates a three-dimensional perspective plot of the elements
of the matrix "z". The mesh surface is defined by the z-
coordinates of points above a rectangular grid in the x-y
plane.
=====================================================================
To draw the graph of a function
z = f(x,y)

mat1-08-graphics
113
G.A. El-Sheikh MATLAB: Introductory Course 114

over a rectangle, one first defines vectors xx and yy, which give partitions of the sides of the
rectangle.

With the function meshdom (mesh domain; called meshgrid in version 4.0) one then creates a
matrix x, each row of which equals xx and whose column length is the length of yy, and
similarly a matrix y, each column of which equals yy, as follows:
>> [x,y] = meshdom(xx,yy);
One then computes a matrix z, obtained by evaluating f entrywise over the matrices x and y,
to which mesh can be applied.
Fig. 5: Three-dimensional Mesh
Example-8.5:
Suppose that we want to draw a graph of
over the square [-2,2] x [-2,2] as
follows:
>> xx = -2:.1:2;
>> yy = xx;
>> [x,y] = meshdom(xx,yy);
>> z = exp(-x.^2 - y.^2);
>> mesh(z)
The result is shown in Fig. 5.

Of course one could replace the first three lines of the preceding with
>> [x,y] = meshdom(-2:.1:2, -2:.1:2);
See the User's Guide for further details regarding mesh. Also see information on functions
plot3, and surf.

Plotting Curves:
‒ plot (x,y); generates a linear plot of the values of x (horizontal axis) and y (vertical axis).
‒ semilogx (x,y); generate a plot of the values of x and y using a logarithmic scale for x
and a linear scale for y.
‒ semilogy (x,y); generate a plot of the values of x and y using a linear scale for x and a
logarithmic scale for y.
‒ loglog(x,y); generate a plot of the values of x and y using logarithmic scales for both x
and y.

Multiple Curves:
‒ plot (x, y, w, z); multiple curves can be plotted on the same graph by using multiple
arguments in a plot command. The variables x, y, w, and z are vectors. Two curves will
be plotted: y vs. x, and z vs. w.
‒ legend (‘string1’, ‘string2’,…); used to distinguish between plots on the same graph

Multiple Figures:
‒ figure (n); used in creation of multiple plot windows. place this command before the
plot() command, and the corresponding figure will be labeled as “Figure n”
‒ close; closes the figure n window.
‒ close all; closes all the figure windows.

mat1-08-graphics
114
G.A. El-Sheikh MATLAB: Introductory Course 115

Subplots: Multiple Plots in One Figure


‒ subplot (m, n, p); m by n grid of windows, with p specifying the current plot as the p th
window
The plots are numbered along first the top row of the figure window, then the second row, and
so on. For example, these statements plot data in four different subregions of the figure
window;
t = 0:pi/10:2*pi;
[X,Y,Z] =
cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)

Example-8.6: (polynomial function)


Plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, and log/log
scale: y = 2 x2 + 7 x + 9

%************************************
%*** polytest03.m ***
%************************************
%*** Plot the polynomial using linear/linear ***
%*** scale, log/linear scale, linear/log scale, ***
%*** and log/log scale ***
%************************************
clc
Polynomial, linear/linear scale Polynomial, log/linear scale
clear 300 300
close all
200 200
% Generate the polynomial:
1

1
y

x1 = linspace (0, 10, 100); 100 100


y1 = 2*x1.^2 + 7*x1 + 9;
0 0
0 5 10 -1 0 1
% plotting the polynomial: 10 10 10
figure (1); Polynomial, linear/log scale Polynomial, log/log scale
3 3
subplot (2,2,1) 10 10
plot (x1,y1,'linewidth',3), grid on
title ('Polynomial, linear/linear scale'); 10
2
10
2

ylabel ('y_1')
1

1
y

1 1
10 10
subplot (2,2,2)
semilogx (x1,y1,'linewidth',3), grid on 0 0
10 10
title ('Polynomial, log/linear scale'); 0 5 10 10
-1
10
0 1
10
ylabel ('y_1') x1 x1

mat1-08-graphics
115
G.A. El-Sheikh MATLAB: Introductory Course 116

subplot (2,2,3)
semilogy (x1,y1,'linewidth',3), grid on
title ('Polynomial, linear/log scale');
xlabel('x_1'), ylabel ('y_1')

subplot (2,2,4)
loglog (x1,y1,'linewidth',3), grid on
title ('Polynomial, log/log scale');
xlabel('x_1'), ylabel ('y_1')

8.9 BAR and Histogram Graphics


The Bar Graph or Bar Chart is a graphical display of data using bars of different heights.
Bar graphs can be used to show how something
changes over time or to compare items. That is,
Bar graphs are used to compare things between
different groups or to track changes over time.

A bar chart is a graph with rectangular bars; the


graph usually compares different categories. For
example, if you had two houses and needed
budgets for each, you could plot them on the same
x-axis with a grouped bar chart, using different
colors to represent each house.

A bar graph can be defined as a chart or a


graphical representation of data, quantities or
numbers using bars or strips. Bar graphs are used
to compare and contrast numbers, frequencies or
other measures of distinct categories of data.

This bar graph shows the different types and


number of school supplies used by students. The
more the height of the bar, the more is the number
of the supply or item used.

Parts of a Bar Graph;


 Title: The title is explains what the graph is
about.
 Scale: The scale is the numbers that show the units
used on the bar graph.
 Labels: Both the side and the bottom of the bar graph
have a label that tells what kind of data is shown. ...
 Bars: The bar is measures the data number.

mat1-08-graphics
116
G.A. El-Sheikh MATLAB: Introductory Course 117

Histograms are used to show distributions of variables while bar charts are used to compare
variables. Histograms plot quantitative data with ranges of
the data grouped into bins or intervals while bar charts plot
categorical data.

Notice that the horizontal axis of Figure 1 consists of


binned times: the first bin includes visits from 0 up to and
including ten minutes, the second bin from 10 up to and
including 20 minutes, and so on. The vertical axis shows
percentages. The area of each bar gives the percentage of
all visitors who spent the amount of time shown in the
corresponding bin. The sum of all areas equals 100%.
Note that it does not make sense to rearrange the bars of a
histogram.

A double bar graph is used to display two sets of data on the same graph. The information in a
double bar graph is related, and it
compares one set of data to another.
A double bar graph is made in the
same way that a single bar graph is
made except that instead of one bar of
data there will be two bars of data.

Here is the data for the number of ice


cream cones sold each week at an ice
cream stand during the months of
July and August;
July August
Week 1 500 800
Week 2 800 900
Week 3 700 600
Week 4 900 800

Create bar and stair graphs using these or other vectors you may define. Of course the 'title'
and 'text' commands can be used with bar and stair graphs;

bar(x,y) and bar(y)


stair (x,y) and stair(y)

The bar graph functions\commands can be summarized as;


bar(y) creates a bar graph with one bar for each element in y. If y is an m-by-n matrix,
then bar creates m groups of n bars.
bar(x,y) draws the bars at the locations specified by x.
bar(--,width) sets the relative bar width, which controls the separation of bars within a group.
Specify width as a scalar value. Use this option with any of the input argument
combinations in the previous syntaxes.
bar(--,style) specifies the style of the bar groups. For example, use 'stacked' to display each
group as one multicolored bar.
bar(--,color) sets the color for all the bars. For example, use 'r' for red bars.

mat1-08-graphics
117
G.A. El-Sheikh MATLAB: Introductory Course 118

bar(--,Name,Value) specifies properties of the bar graph using one or more name-value pair
arguments. Only bar graphs that use the default 'grouped' or 'stacked' style support
setting bar properties. Specify the name-value pair arguments after all other input
arguments. For a list of properties, see Bar Properties.
bar(ax,--) plots into the axes specified by ax instead of into the current axes (gca). The
option ax can precede any of the input argument combinations in the previous syntaxes.
b = bar(---) returns one or more Bar objects. If y is a vector, then bar creates one Bar object.
If y is a matrix, then bar returns a Bar object for each series. Use b to set properties of
the bars after displaying the bar graph.

Examples:
Create Bar Graph
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y)

Specify the bar locations along the x-axis;


x = 1900:10:2000;
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(x,y)

Specify Bar Width


Set the width of each bar to 40 percent of the total
space available for each bar;
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,0.4)

mat1-08-graphics
118
G.A. El-Sheikh MATLAB: Introductory Course 119

Display Groups of Bars


Display four groups of three bars;
y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y)

Specify Categorical Data


One way to indicate categories for your bars is to specify X as a categorical array.
The bar function uses a sorted list of the categories, so the bars might display in a different
order than you expect. To preserve the order, call the reordercats function.
Define X as categorical array, and call the reordercats function to specify the order for the
bars. Then define Y as a vector of bar heights and display the bar graph;
X = categorical({'Small','Medium','Large','Extra Large'});
X = reordercats(X,{'Small','Medium','Large','Extra Large'});
Y = [10 21 33 52];
bar(X,Y)

Specify Bar Color


y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,'r')

Specify Bar and Outline Colors


Set the bar interior color and outline color using RGB triplets. Set the width of the bar outline;

mat1-08-graphics
119
G.A. El-Sheikh MATLAB: Introductory Course 120

y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,'FaceColor',[0 .5 .5],'EdgeColor',[0 .9 .9],'LineWidth',1.5)

Create a bar chart with error bars using both the bar and error-bar functions;
x = 1:13;
data = [37.6 24.5 14.6 18.1 19.5 8.1 28.5 7.9 3.3 4.1 7.9 1.9 4.3]';
errhigh = [2.1 4.4 0.4 3.3 2.5 0.4 1.6 0.8 0.6 0.8 2.2 0.9 1.5];
errlow = [4.4 2.4 2.3 0.5 1.6 1.5 4.5 1.5 0.4 1.2 1.3 0.8 1.9];
bar(x,data)
hold on
er = errorbar(x,data,errlow,errhigh);
er.Color = [0 0 0];
er.LineStyle = 'none';
hold off

Histograms in MATLAB
Basic Histogram with MATLAB's hist Function
% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

% some random points


x = normrnd(5,1,100,1);

% a simple histogram
fig = figure;
hist(x)

%--PLOTLY--%

mat1-08-graphics
120
G.A. El-Sheikh MATLAB: Introductory Course 121

% Strip MATLAB<sup>&reg;</sup> style by default!


response = fig2plotly(fig, 'filename', 'matlab-basic-
histogram');
plotly_url = response.url;

Stacked Histogram with the hist Function


% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

% stacked histogram
sd1 = 0.1;
mu1 = 0;
data1 = mu1+ sd1.*randn(5000,1);
sd2 = 0.1;
mu2 = 0;
data2 = mu2+ sd2.*randn(5000,1);

% bin specs.
nbins = 50;
bound = 1;
bins = linspace(-bound,bound,nbins);

fig = figure;

% first histogram
y1 = hist(data1, bins);

% second histogram
y2 = hist(data2, bins);

% stacked histograms
bar([y1.' y2.'],'stacked')

% relabelx-axis range/ticks
xd = findobj('-property','XData');

mat1-08-graphics
121
G.A. El-Sheikh MATLAB: Introductory Course 122

for i=1:2
dat = get(xd(i),'XData');
dat = 2*dat/nbins - bound;
set(xd(i),'XData',dat);
end

%--PLOTLY--%

% Strip MATLAB<sup>&reg;</sup> style by default!


response = fig2plotly(fig, 'filename', 'matlab-stacked-
histogram');
plotly_url = response.url;

Histogram with Line


% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

x = 5+2*randn(1000,1);
h = histc(x,(0:9));
stem(h,'b')

response = fig2plotly;
plotly_url = response.url;

mat1-08-graphics
122
G.A. El-Sheikh MATLAB: Introductory Course 123

Overlaid Histogram with hist


% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

% overlaid histogram
sd1 = 0.1;
mu1 = 0;
data1 = mu1+ sd1.*randn(5000,1);
sd2 = 0.1;
mu2 = 0.3;
data2 = mu2+ sd2.*randn(5000,1);
%bin specs.
nbins = 50;
bound = 1;
bins = linspace(-bound,bound,nbins);

fig = figure;

% first histogram
y1 = hist(data1, bins);
% second histogram
y2 = hist(data2, bins);

% overlay histograms
bar(y1.');
hold on;
bar(y2.','r');

% relabel x-axis range/ticks


xd = findobj('-property','XData');

for i=1:2
dat = get(xd(i),'XData');
dat = 2*dat/nbins - bound;
set(xd(i),'XData',dat);
end

%--PLOTLY--%

% Strip MATLAB<sup>&reg;</sup> style by default!


response = fig2plotly(fig, 'filename', 'matlab-overlaid-
histogram');
plotly_url = response.url;

mat1-08-graphics
123
G.A. El-Sheikh MATLAB: Introductory Course 124

Horizontal Histogram using hist and bar


% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

% horizontal histogram
sd = 0.1;
mu = 1;
data = mu + sd*randn(1,5000);

% bin specs.
nbins = 50;

% make/plot histogram of data


fig = figure;
[h1 bins]= hist(data,nbins);
barh(bins,h1);

%--PLOTLY--%

% Strip MATLAB<sup>&reg;</sup> style by default!


response = fig2plotly(fig, 'filename', 'matlab-horizontal-
histogram');
plotly_url = response.url;

mat1-08-graphics
124
G.A. El-Sheikh MATLAB: Introductory Course 125

Basic Histogram
% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

x = randn(500,1);

data = {...
struct(...
'x', x, ...
'type', 'histogram')...
};
response = plotly(data, struct('filename', 'basic-histogram',
'fileopt', 'overwrite'));
plot_url = response.url

mat1-08-graphics
125
G.A. El-Sheikh MATLAB: Introductory Course 126

Horizontal Histogram
% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

y = randn(500,1);

data = {...
struct(...
'y', y, ...
'type', 'histogram')...
};
response = plotly(data, struct('filename', 'horizontal-
histogram', 'fileopt', 'overwrite'));
plot_url = response.url

Overlaid Histgram
% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

x0 = randn(500,1);
x1 = randn(500,1)+1;

trace1 = struct(...
'x', x0, ...
'opacity', 0.75, ...
'type', 'histogram');
trace2 = struct(...
'x', x1, ...
'opacity', 0.75, ...
'type', 'histogram');
data = {trace1, trace2};
layout = struct('barmode', 'overlay');
response = plotly(data, struct('layout', layout, 'filename',
'overlaid-histogram', 'fileopt', 'overwrite'));
plot_url = response.url

mat1-08-graphics
126
G.A. El-Sheikh MATLAB: Introductory Course 127

Stacked Histograms
% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

x0 = randn(500,1);
x1 = randn(500,1)+1;

trace1 = struct(...
'x', x0, ...
'type', 'histogram');
trace2 = struct(...
'x', x1, ...
'type', 'histogram');
data = {trace1, trace2};
layout = struct('barmode', 'stack');
response = plotly(data, struct('layout', layout, 'filename',
'stacked-histogram', 'fileopt', 'overwrite'));
plot_url = response.url

mat1-08-graphics
127
G.A. El-Sheikh MATLAB: Introductory Course 128

Colored and Styled Histograms


% Learn about API authentication here:
https://plotly.com/matlab/getting-started
% Find your api_key here: https://plotly.com/settings/api

x0 = randn(500,1);
x1 = randn(500,1)+1;

trace1 = struct(...
'x', x0, ...
'histnorm', 'count', ...
'name', 'control', ...
'autobinx', false, ...
'xbins', struct(...
'start', -3.2, ...
'end', 2.8, ...
'size', 0.2), ...
'marker', struct(...
'color', 'fuchsia', ...
'line', struct(...
'color', 'grey', ...
'width', 0), ...
'opacity', 0.75), ...
'type', 'histogram');
trace2 = struct(...
'x', x1, ...
'name', 'experimental', ...
'autobinx', false, ...
'xbins', struct(...
'start', -1.8, ...
'end', 4.2, ...
'size', 0.2), ...
'marker', struct('color', 'rgb(255, 217, 102)'), ...
'opacity', 0.75, ...
'type', 'histogram');
data = {trace1, trace2};
layout = struct(...
'title', 'Sampled Results', ...
'xaxis', struct('title', 'Value'), ...
'yaxis', struct('title', 'Count'), ...
'barmode', 'overlay', ...
'bargap', 0.25, ...
'bargroupgap', 0.3);
response = plotly(data, struct('layout', layout, 'filename',
'style-histogram', 'fileopt', 'overwrite'));
plot_url = response.url

mat1-08-graphics
128
G.A. El-Sheikh MATLAB: Introductory Course 129

8.10 Creating Hexagonal Cell in MATLAB


8.10.1 Introduction
Regular Polygon
In Euclidean geometry, a regular polygon is a polygon that is equiangular (all angles are
equal in measure) and equilateral (all sides have the same length). Regular polygons may be
either convex or star. In the limit, a sequence of regular polygons with an increasing number
of sides approximates a circle, if the perimeter or area is fixed, or a regular apeirogon
(effectively a straight line), if the edge length is fixed.

General properties
A regular n-sided polygon has rotational symmetry of order n. All vertices of a regular
polygon lie on a common circle (the circumscribed circle); i.e. they are concyclic points. That
is, a regular polygon is a cyclic polygon. Together with the property of equal-length sides, this
implies that every regular polygon also has an inscribed circle or in circle that is tangent to
every side at the midpoint. Thus a regular polygon is a tangential polygon. A regular n-sided
polygon can be constructed with compass and straightedge if and only if the odd prime factors
of n are distinct Fermat primes.

Symmetry
The symmetry group of an n-sided regular polygon is dihedral group Dn (of order 2n): D2, D3,
D4, ... It consists of the rotations in Cn, together with reflection symmetry in n axes that pass
through the center. If n is even then half of these axes pass through two opposite vertices, and
the other half through the midpoint of opposite sides. If n is odd then all axes pass through a
vertex and the midpoint of the opposite side.

Names of Polygons
You may need to first identify how many sides are present in the polygon. Each polygon has a
prefix that indicates the number of sides it has. Here are the names of polygons with up to
twenty sides (n):
 Quadrilateral/tetragon: 4 sides
 Pentagon: 5 sides
 Hexagon: 6 sides
 Heptagon: 7 sides
 Octagon: 8 sides
 Nonagon/Enneagon: 9 sides
 Decagon: 10 sides
 Hendecagon: 11 sides
 Dodecagon: 12 sides
 Triskaidecagon/tridecagon: 13 sides
 Tetrakaidecagon/tetradecagon: 14 sides
 Pentadecagon: 15 sides
 Hexadecagon: 16 sides
 Heptadecagon: 17 sides
 Octadecagon: 18 sides
 Enneadecagon: 19 sides
 Icosagon: 20 sides
 Note that a triangle has no diagonals.

Mat1-08-graphics2
129
G.A. El-Sheikh MATLAB: Introductory Course 130

Angles of Polygons
In this section we will learn;
 how to calculate the sum of interior angles of a polygon using the sum of angles in a
triangle
 the formula for the sum of interior angles in a polygon
 how to solve problems using the sum of interior angles
 the formula for the sum of exterior angles in a polygon
 how to solve problems using the sum of exterior angles

All the polygons in this lesson are assumed to be convex polygons.


The following diagrams give the formulas for the sum of the interior angles of a polygon and
the sum of exterior angles of a polygon. Scroll down the page if you need more examples and
explanation.

Sum of Interior Angles of a Polygon


We first start with a triangle (which is a polygon with the fewest number of sides). We know
that the sum of interior angles in a triangle is 180°. This is also called the Triangle Sum
Theorem.

Mat1-08-graphics2
130
G.A. El-Sheikh MATLAB: Introductory Course 131

Next, we can figure out the sum of interior angles of any polygon by dividing the polygon
into triangles. We can separate a polygon into triangles by drawing all the diagonals that can
be drawn from one single vertex.
In the quadrilateral shown below, we can draw only one diagonal from vertex A to vertex B.
So, a quadrilateral can be separated into two triangles.

The sum of angles in a triangle is 180°. Since a quadrilateral is


made up of two triangles the sum of its angles would be
180° × 2 = 360°
The sum of interior angles in a quadrilateral is 360º

A pentagon (five-sided polygon) can be divided into three triangles. The sum of its angles will
be 180° × 3 = 540°
The sum of interior angles in a pentagon is 540°.
A hexagon (six-sided polygon) can be divided into four triangles. The sum of its angles will
be 180° × 4 = 720°
The sum of interior angles in a hexagon is 720°.

Formula for the sum of interior angles


We can see from the above examples that the number of triangles in a polygon is always two
less than the number of sides of the polygon. We can then generalize the results for a n-sided
polygon to get a formula to find the sum of the interior angles of any polygon.

The following diagram shows the formula for the sum of interior angles of an n-sided polygon
and the size of an interior angle of a n-sided regular polygon. Scroll down the page for more
examples and solutions on the interior angles of a polygon.

Example:
Find the sum of the interior angles of a heptagon (7-sided)
Solution:
Step 1: Write down the formula (n - 2) × 180°
Step 2: Plug in the values to get (7 - 2) × 180° = 5 × 180° = 900°
Answer: The sum of the interior angles of a heptagon (7-sided) is 900°.

Example:
Find the interior angle of a regular octagon.
Solution:
Step 1: Write down the formula

Mat1-08-graphics2
131
G.A. El-Sheikh MATLAB: Introductory Course 132

Step 2: Plug in the values to get

Answer: Each interior angle of an octagon (8-sided) is 135°.

The Exterior Angle is the angle between


any side of a shape, and a line extended
from the next side.

Another example:

When we add up the Interior Angle and


Exterior Angle we get a straight line 180°.

Interior Angle = 180° − Exterior Angle


Exterior angle = 360°/n
 Interior Angle = 180° − 360°/n
Which can be rearranged like this:
Interior Angle = 180° − 360°/n
= (n × 180° / n) − (2 × 180° / n)
= (n−2) × 180°/n
So,
Interior Angle = (n−2) × 180° / n

Circumcircle, Incircle, Radius and Apothem


Sounds quite musical if you repeat it a few times, but
they are just the names of the "outer" and "inner" circles
(and each radius) that can be drawn on a polygon like
the shown.

The "outside" circle is called a circumcircle, and it


connects all vertices (corner points) of the polygon.
The radius of the circumcircle is also the radius of the
polygon.

The "inside" circle is called an incircle and it just


touches each side of the polygon at its midpoint.
The radius of the incircle is the apothem of the polygon.
(Not all polygons have those properties, but triangles
and regular polygons do).

Mat1-08-graphics2
132
G.A. El-Sheikh MATLAB: Introductory Course 133

8.10.2 Plotting Algorithm


1) First you should know, how to plot unit circle in MATLAB.
x 2  y2  r 2
x  r cos()
y  r sin( )

2) All vertices of a regular polygon lie on a


common circle (the circumscribed circle); i.e.
they are concyclic points. That is, a regular
polygon is a cyclic polygon.
3) So we shall use this concept to plot regular
hexagon.
4) Just we have to keep the increment of angle as
60 degree (pi/3).

%************************************ Polar plot of a polygon with No. of sides = 8 and radius R= 1

%*** polygon01.m *** 90


1
120 60
%************************************ 0.8
%*** Demonstrates MATLAB commands ***
0.6
%*** to plot a polygon grid representing a *** 150 30
0.4
%*** cellular network ***
%************************************ 0.2

clc 180 0
clear
close all

%*** Creating a polygon using polar-command 210 330

n1 = 4; %*** Number of sides in half-plan


r0 = 1; %*** Radius of tangent-circle 240 300
270
theta1 = 0:pi/n1:2*pi;
r1 = r0*ones(1,length(theta1));
figure Ploting a polygon with No. of sides = 6 around the origin
1
polar(theta1,r1), grid on
title(['Polar plot of a polygon with No. of sides = ' ... 0.8

num2str(2*n1) ' and radius R= ' num2str(r0)]) 0.6

0.4
%*** Creating a polygon using plot-command
n2 = 6; %*** 0.2

theta2 = 0:360/n2:360; % Step=1 for circle, 60 for 0


hexagon
-0.2
x2 = cosd(theta2);
-0.4
y2 = sind(theta2);
-0.6
figure -0.8
plot(x2, y2, 'b-', 'Linewidth', 3), grid on
-1
axis square; -1 -0.5 0 0.5 1

Mat1-08-graphics2
133
G.A. El-Sheikh MATLAB: Introductory Course 134

title(['Ploting a polygon with No. of sides = ' ...


num2str(n2) ' around the origin'])

%*** function polygon01f(C3,x3,y3)


%*** C3= side size; (x3,y3) hexagon center coordinates;
C3 = 10;
x3 = 5; y3 = 8;

figure Ploting a hexagon with size = 10 around the center at (5 8)


polygon01f(C3,x3,y3) 18

title(['Ploting a hexagon with size = ' ... 16


num2str(C3) ' around the center at (' ...
14
num2str(x3) ' ' num2str(y3) ')'])
12
%************************************ 10
%*** polygon01f.m ***
%************************************ 8

%*** Demonstrates MATLAB commands *** 6


%*** to plot hexagonal grid representing a ***
4
%*** cellular network ***
%*** function polygon01f(C3,x3,y3) *** 2
%*** C3= side size *** 0
%*** (x3,y3) hexagon center coordinates ***
%************************************ -2
-5 0 5 10 15

function polygon01f(C3,x3,y3)
%*** C3= side size; (x3,y3) hexagon center coordinates;
x3f = C3*[-1 -0.5 0.5 1 0.5 -0.5 -1] + x3;
y3f = C3*sqrt(3)*[0 -0.5 -0.5 0 0.5 0.5 0] + y3;
plot(x3f,y3f,'r','linewidth',4); grid on
axis square;

The centroid is simply the mean average computed separately for each dimension.
To find the centroid of each of the rows of your matrix A, you can call the mean function:
centroid = mean(A);

The above call to mean operates on rows by default. If you want to get the centroid of the
columns of A, then you need to call mean as follows:
centroid = mean(A, 2);

Mat1-08-graphics2
134
G.A. El-Sheikh MATLAB: Introductory Course 135

8.10.3 Generating an Array of Hexagonal Shape Pattern


PATCH Create patch;

PATCH(X,Y,C) adds the "patch" or filled 2-D polygon defined by vectors X and Y to the
current axes. If X and Y are matrices of the same size, one polygon ("face") per column is
added. C specifies the color of the face(s) ("flat" coloring), or the vertices ("interpolated"
coloring), for which bilinear interpolation is used to determine the interior color of the
polygon.

For both vector or matrix X and Y, if C is a string, each face is filled with 'color'. 'color' can
be 'r','g','b','c','m','y', 'w', or 'k'. If C is a scalar it specifies the color of the face(s) by indexing
into the colormap. A 1x3 vector C is always assumed to be an RGB triplet specifying a color
directly.

For vector X and Y, if C is a vector of the same length, it specifies the color of each vertex as
indices into the colormap and bilinear interpolation is used to determine the interior color of
the polygon ("interpolated" shading).

When X and Y are matrices, if C is a 1xn, where n is the number of columns in X and Y, then
each face j=1:n is flat colored by the colormap index C(j). Note the special case of a 1x3 C is
always assumed to be an RGB triplet ColorSpec and specifies the same flat color for each
face. If C is a matrix the same size as X and Y, then it specifies the colors at the vertices as
colormap indices and bilinear interpolation is used to color the faces.
If C is 1xnx3, where n is the number of columns of X and Y, then each face j is flat colored
by the RGB triplet C(1,j,:).
If C is mxnx3, where X and Y are mxn, then each vertex (X(i,j),Y(i,j)) is colored by the RGB
triplet C(i,j,:) and the face is colored using interpolation.

PATCH(X,Y,Z,C) creates a patch in 3-D coordinates. Z must be the same size as X and Y.

PATCH returns a handle to a Patch object. Patches are children of AXES objects.

The X,Y,C triple (X,Y,Z,C quad for 3-D) can be followed by parameter/value pairs to specify
additional properties of the Patch. The X,Y,C triple (X,Y,Z,C quad for 3-D) can be omitted
entirely, and all properties specified using parameter/value pairs.

Patch objects also support data specified using the properties Faces, Vertices, and
FaceVertexCData (see the reference manual for more information). These properties do not
have a convenience syntax, but may be specified using param-value pairs. Patch data
specified as XData, YData, ZData, and CData is translated and stored internally as Faces,
Vertices, and FaceVertexCData, and the original matrices are not stored. When GET is used
to query XData, YData, ZData, or CData, the returned value is computed by translating from
Faces, Vertices, and FaceVertexCData.

GET(H), where H is a patch handle, displays a list of patch object properties and their current
values. SET(H) will display a list of patch object properties and legal property values.

Mat1-08-graphics2
135
G.A. El-Sheikh MATLAB: Introductory Course 136

The following code generates an array of values (i.e. H matrix here) having a dimension of
256x256 which is a square matrix (pattern looks like some black and white strips). I would
like to modify this square matrix into a regular hexagonal shape through MATLAB code.
mx=5;
my=10;
[x, y]=meshgrid(-1:2/255:+1, -1:2/255:+1);
H=(cos((x*pi*mx)+(y*pi*my)))>0;
figure(1)
imagesc(H); colormap gray; axis image; axis off

Alternatively;
%************************************
%*** polygon04.m ***
%************************************
%*** Demonstrates MATLAB commands ***
%*** to plot hexagonal grid representing a ***
%*** cellular network ***
%************************************
clc
clear
close all

n1 =10;
b1 =10;
C1 = rand(n1,b1);
xhex = [0 1 2 2 1 0]; % x-coordinates of the vertices
yhex = [2 3 2 1 0 1]; % y-coordinates of the vertices

for i=1:b1
j=i-1;
for k=1:n1
m=k-1;
patch((xhex+mod(k,2))+2*j,...
yhex+2*m,C1(k,i)) % make a hexagon at [2i,2j]
hold on
end
end
axis equal
grid on

This code will generate hexagons at [2i,2j] co-ordinates. You can rescale the axis
(TickLabels) or rescale the vertices of the hexagon.
The mod(k,2) is used to shift the hexagons by 1 in alternate rows so that they fit; a random
matrix is used. You can simply change the matrix C to your data and plot the grid
accordingly.

Mat1-08-graphics2
136
G.A. El-Sheikh MATLAB: Introductory Course 137

20

18

16

14

12

10

0
0 5 10 15 20

8.10.4 Hexagonal grid representing a cellular network as used in


mobile communication systems
It is required to generate a hexagonal grid that represents a cellular network where each
hexagon has a specific behaviour. The question is how does one go from a square grid to hex
grid (transfer matrix)?. This is can be done as,
[X,Y] = meshgrid(0:60);
figure(1), plot(X,Y,'b')
hold on, plot(Y,X,'b')
axis square

Alternatively;
%************************************
%*** polygon06.m ***
%************************************
%*** Demonstrates MATLAB commands ***
%*** to plot hexagonal grid representing a ***
%*** cellular network ***
%************************************
clc
clear
close all

% Define input data:


M_max = 14; % number of cells in vertical direction
N_max = 10; % number of cells in horizontal direction
trans = 1; % hexagon orientation (0 or 1)

Mat1-08-graphics2
137
G.A. El-Sheikh MATLAB: Introductory Course 138

%*** Plotting:
figure
hold on
for m = -M_max:M_max
for n = -N_max:N_max
center = [0.5 sqrt(3)/2] + m*[0 -sqrt(3)] + n*[3/2 sqrt(3)/2];
if ~trans
plot([center(1)-1 center(1)],[center(2) center(2)])
plot([center(1) center(1)+1/2],[center(2) center(2)+sqrt(3)/2])
plot([center(1) center(1)+1/2],[center(2) center(2)-sqrt(3)/2])
else % exchange the two arguments to `plot`
plot([center(2) center(2)],[center(1)-1 center(1)])
plot([center(2) center(2)+sqrt(3)/2],[center(1) center(1)+1/2])
plot([center(2) center(2)-sqrt(3)/2],[center(1) center(1)+1/2])
end
end
end

plot([-15 15],[0 0],'-.') % adjust length manually


plot([-15 15],[-15*sqrt(3) 15*sqrt(3)],'-.') % adjust length manually
axis image
set(gca,'xtick',[])
set(gca,'ytick',[])
axis([-10 10 -13.3 13.3]) % adjust axis size manually
set(gca,'Visible','on') % handy for printing the image

This is the image generated with the above data:

Mat1-08-graphics2
138
G.A. El-Sheikh MATLAB: Introductory Course 139

8.10.5 Patch Objects


A patch graphics object is composed of one or more polygons that may or may not be
connected. Patches are useful for modeling real-world objects such as airplanes or
automobiles, and for drawing 2- or 3-D polygons of arbitrary shape.

In contrast, surface objects are rectangular grids of quadrilaterals and are better suited for
displaying planar topographies such as the values of mathematical functions of two variables,
the contours of data in a rectangular plane, or parameterized surfaces such as spheres.

A number of MATLAB® functions create patch objects; fill, fill3, isosurface, isocaps, some of
the contour functions, and patch. This section concentrates on use of the patch function.

You define a patch by specifying the coordinates of its vertices and some form of color data.
Patches support a variety of coloring options that are useful for visualizing data superimposed
on geometric shapes. There are two ways to specify a patch:
 By specifying the coordinates of the vertices of each polygon, which are connected to form
the patch
 By specifying the coordinates of each unique vertex and a matrix that specifies how to
connect these vertices to form the faces

The second technique is preferred for multifaceted patches because it generally requires less
data to define the patch; vertices shared by more than one face need be defined only once.

Behavior of the patch Function


There are two forms of the patch function -- high-level syntax and low-level syntax. The
behavior of the patch function differs somewhat depending on which syntax you use.

High-Level Syntax
When you use the high-level syntax, MATLAB automatically determines how to color each
face based on the color data you specify. The high-level syntax enables you to omit the
property names for the x-, y-, and z-coordinates and the color data, as long as you specify
these arguments in the correct order;
patch(x-coordinates, y-coordinates, z-coordinates, colordata)

However, you must specify color data so MATLAB can determine what type of coloring to
use. If you do not specify color data, MATLAB returns an error.
x = [0 1 1 0];
y = [0 0 1 1];
patch(x,y)
Error using patch
Not enough input arguments.

Low-Level Syntax
The low-level syntax accepts only property name/property value pairs as arguments and does
not automatically color the faces unless you also change the value of the FaceColor property.
For example, the statement
patch('XData', x, 'YData', y)
draws a patch with black face color because the factory default value for
the FaceColor property is the color black.
get(groot,'FactoryPatchFaceColor')

Mat1-08-graphics2
139
G.A. El-Sheikh MATLAB: Introductory Course 140

ans =
0 0 0

Interpreting the Color Argument


When you use the high-level syntax, MATLAB interprets the third (or fourth if there are z-
coordinates) argument as color data. If you intend to define a patch with x-, y-, and z-
coordinates, but leave out the color, MATLAB interprets the z-coordinates as color data, and
then draws a 2-D patch. For example,
patch(x,y,1:length(x))
draws a patch with all vertices at z = 0, colored by interpolating the vertex colors (since there
is one color for each vertex), whereas
patch(x,y,1:length(x),'y')
draws a patch with vertices at increasing values of z, colored yellow.

Creating a Single Polygon


A polygon is simply a patch with one face. To create a polygon, specify the coordinates of the
vertices and color data with a statement of the form
patch(x-coordinates,y-coordinates,[z-coordinates],colordata)

For example, these statements display a 10-sided polygon with a yellow face enclosed by a
black edge. The axis equal command
produces a correctly proportioned
polygon;
t = 0:pi/5:2*pi;
figure
patch(sin(t),cos(t),'y')
axis equal

The first and last vertices need not


coincide; MATLAB automatically
closes each polygonal face of the
patch. In fact, it is generally better to
define each vertex only once,
particularly if you are using
interpolated face coloring.

Interpolated Face Colors


You can control many aspects of the patch coloring. For example, instead of specifying a
single color, provide a range of numerical values that map the color at each vertex to a color
in the figure colormap.
a = t(1:length(t)-1); %remove redundant vertex definition
figure
patch(sin(a),cos(a),1:length(a),'FaceColor','interp')
axis equal

Mat1-08-graphics2
140
G.A. El-Sheikh MATLAB: Introductory Course 141

MATLAB now interpolates the colors across the face of the patch. You can color the edges of
the patch the same way, by setting the edge colors to be interpolated. The command is
patch(sin(a),cos(a),1:length(a),'EdgeColor','interp')

How Patch Data Relates to a Colormap


provides more information on options
for coloring patches.

Specifying Patch Properties


You can specify properties as property name/property value pairs, structure arrays, and cell
arrays (see the set and get reference pages for examples of how to specify these data types).
There are two patch properties that specify color:
 CData -- Use when specifying x-, y-, and z-coordinates (XData, YData, ZData).
 FaceVertexCData -- Use when specifying vertices and connection matrix
(Vertices and Faces).

The CData and FaceVertexCData properties accept color data as indexed or true color (RGB)
values. See the CData and FaceVertexCData property descriptions for information on how to
specify color.

Indexed color data can represent either direct indices into the colormap or scaled values that
map the data linearly to the entire colormap (see the caxis function for more information on
this scaling). The CDataMapping property determines how MATLAB interprets indexed
color data.

Mat1-08-graphics2
141
G.A. El-Sheikh MATLAB: Introductory Course 142

Description
patch is the low-level graphics function for creating patch graphics objects. A patch object is
one or more polygons defined by the coordinates of its vertices. You can specify the coloring
and lighting of the patch.

patch(X,Y,C) adds the filled two-dimensional patch to the current axes. The elements
of X and Y specify the vertices of a polygon. If X and Y are matrices, MATLAB draws one
polygon per column. C determines the color of the patch. It can be a single ColorSpec, one
color per face, or one color per vertex (see "Remarks"). If C is a 1-by-3 vector, it is assumed
to be an RGB triplet, specifying a color directly.

patch(X,Y,Z,C) creates a patch in three-dimensional coordinates.


patch(FV) creates a patch using structure FV, which contains the fields vertices, faces, and
optionally facevertexdata. These fields correspond to the Vertices, Faces, and
FaceVertexCData patch properties.

patch(...'PropertyName',PropertyValue...) follows the X, Y, (Z), and C arguments with


property name/property value pairs to specify additional patch properties.
patch('PropertyName',PropertyValue,...) specifies all properties using property name/property
value pairs. This form enables you to omit the color specification because MATLAB uses the
default face color and edge color unless you explicitly assign a value to the FaceColor and
EdgeColor properties. This form also allows you to specify the patch using the Faces and
Vertices properties instead of x-, y-, and z-coordinates.

handle = patch(...) returns the handle of the patch object it creates.

Remarks
Unlike high-level area creation functions, such as fill or area, patch does not check the
settings of the figure and axes NextPlot properties. It simply adds the patch object to the
current axes.

If the coordinate data does not define closed polygons, patch closes the polygons. The data
can define concave or intersecting polygons. However, if the edges of an individual patch face
intersect themselves, the resulting face may or may not be completely filled. In that case, it is
better to break up the face into smaller polygons.

Color Data Interpretation


You can specify patch colors as
 A single color for all faces
 One color for each face, enabling flat coloring
 One color for each vertex, enabling interpolated coloring

The following tables summarize how MATLAB interprets color data defined by the CData
and FaceVertexCData properties.

Mat1-08-graphics2
142
G.A. El-Sheikh MATLAB: Introductory Course 143

Interpretation of the CData Property;


[X,Y,Z]Data CData Required for Results Obtained
Dimensions Indexed True Color
m-by-n scalar 1-by-1-by-3 Use the single color specified for all patch faces.
Edges can be only a single color.
m-by-n 1-by-n 1-by-n-by-3 Use one color for each patch face. Edges can be only
(n >= 4) a single color.
m-by-n m-by-n m-by-n-3 Assign a color to each vertex. Patch faces can be flat
(a single color) or interpolated. Edges can be flat or
interpolated.

Vertices Faces FaceVertexCData Results Obtained


Required for
Dimensions Dimensions Indexed True
Color
m-by-n k-by-3 scalar 1-by-3 Use the single color specified for all patch
faces. Edges can be only a single color.
m-by-n k-by-3 k-by-1 k-by-3 Use one color for each patch face. Edges
can be only a single color.
m-by-n k-by-3 m-by-1 m-by-3
Assign a color to each vertex. Patch faces
can be flat (a single color) or interpolated.
Edges can be flat or interpolated.
Interpretation of the FaceVertexCData Property

Examples
This example creates a patch object using two different methods:
 Specifying x-, y-, and z-coordinates and color data (XData, YData, ZData, and
CData properties)
 Specifying vertices, the connection matrix, and color data (Vertices, Faces,
FaceVertexCData, and FaceColor properties)

Specifying X, Y, and Z Coordinates


The first approach specifies the coordinates of each vertex. In this example, the coordinate
data defines two triangular faces, each having
three vertices. Using true color, the top face is set
to white and the bottom face to gray.
x = [0 0;0 1;1 1];
y = [1 1;2 2;2 1];
z = [1 1;1 1;1 1];
tcolor(1,1,1:3) = [1 1 1];
tcolor(1,2,1:3) = [.7 .7 .7];
patch(x,y,z,tcolor)

Mat1-08-graphics2
143
G.A. El-Sheikh MATLAB: Introductory Course 144

Notice that each face shares two vertices with the other face (V 1-V4 and V3-V5).

Specifying Vertices and Faces


The Vertices property contains the coordinates of each unique vertex defining the patch.
The Faces property specifies how to connect these vertices to form each face of the patch. For
this example, two vertices share the same location so you need to specify only four of the six
vertices. Each row contains the x-, y-, and z-coordinates of each vertex;
 vert = [0 1 1;0 2 1;1 2 1;1 1 1];

There are only two faces, defined by connecting the vertices in the order indicated.
 fac = [1 2 3;1 3 4];

To specify the face colors, define a 2-by-3 matrix containing two RGB color definitions.
 tcolor = [1 1 1;.7 .7 .7];

With two faces and two colors, MATLAB can color each face with flat shading. This means
you must set the FaceColor property to flat, since the faces/vertices technique is available
only as a low-level function call (i.e., only by specifying property name/property value pairs).

Create the patch by specifying the Faces,


Vertices, and FaceVertexCData properties as
well as the FaceColor property;
patch('Faces',fac,'Vertices',vert, …
'FaceVertexCData',tcolor,...
'FaceColor','flat')

Specifying only unique vertices and their


connection matrix can reduce the size of the data
for patches having many faces. See the
descriptions of the Faces, Vertices, and
FaceVertexCData properties for information on
how to define them.

MATLAB does not require each face to have the same number of vertices. In cases where
they do not, pad the Faces matrix with NaNs. To define a patch with faces that do not close,
add one or more NaNs to the row in the Vertices matrix that defines the vertex you do not
want connected.

Object Hierarchy

Setting Default Properties


You can set default patch properties on the axes, figure, and root levels:

Mat1-08-graphics2
144
G.A. El-Sheikh MATLAB: Introductory Course 145

 set(0,'DefaultPatchPropertyName',PropertyValue...)
 set(gcf,'DefaultPatchPropertyName',PropertyValue...)
 set(gca,'DefaultPatchPropertyName',PropertyValue...)

Shrinkfaces
Syntax
shrinkfaces(p,sf)
nfv = shrinkfaces(p,sf)
nfv = shrinkfaces(fv,sf)
shrinkfaces(p)
nfv = shrinkfaces(f,v,sf)
[nf,nv] = shrinkfaces(...)

Description
shrinkfaces(p,sf) shrinks the area of the faces in patch p to shrink factor sf. A shrink factor of 0.6
shrinks each face to 60% of its original area. If the patch contains shared vertices, the
MATLAB® software creates nonshared vertices before performing the face-area reduction.

nfv = shrinkfaces(p,sf) returns the face and vertex data in the struct nfv, but does not set
the Faces and Vertices properties of patch p.

nfv = shrinkfaces(fv,sf) uses the face and vertex data from the struct fv.
shrinkfaces(p) and shrinkfaces(fv) (without specifying a shrink factor) assume a shrink factor of
0.3.

nfv = shrinkfaces(f,v,sf) uses the face and vertex data from the arrays f and v.

[nf,nv] = shrinkfaces(...) returns the face and vertex data in two separate arrays instead of a
struct.

Examples
Load the flow data set, which represents the speed profile of a submerged jet within an
infinite tank. Create two isosurfaces that provide a before and after view of the effects of
shrinking the face size.
Sample the flow data at every other point
using reducevolume and then use isosurface to
generate the faces and vertices data. Draw the
first isosurface. Then set up the view and add a
title.

[x,y,z,v] = flow;
[x,y,z,v] = reducevolume(x,y,z,v,2);
fv = isosurface(x,y,z,v,-3);
p1 = patch(fv);
p1.FaceColor = 'red';
p1.EdgeColor = [0.5 0.5 0.5];
daspect([1 1 1]);
view(3);
axis tight
title('Original')

Mat1-08-graphics2
145
G.A. El-Sheikh MATLAB: Introductory Course 146

Use shrinkfaces to modify the face and vertex data and draw a second patch;
figure
p2 = patch(shrinkfaces(fv,.3));
p2.FaceColor = 'red';
p2.EdgeColor = [0.5 0.5 0.5];
daspect([1 1 1]);
view(3);
axis tight
title('After Shrinking')

Mat1-08-graphics2
146
G.A. El-Sheikh MATLAB: Introductory Course 147

Polygons' Equations
Polygons, those many-sided objects so popular in geometry circles, are subject to their own
formulas that help you find the area and angles of various geometrical shapes. Have a look
at the most common formulas for working with polygons:

Area of Polygon
The area of a polygon is the total space enclosed within the
shape. The measurement is done in square units.
As we know, a polygon can be regular or irregular.
Regular polygons have a definite dimension to their sides,
and thus their areas are easy to calculate compared to
irregular polygons where the sides have no fixed
dimension. Let us learn the basic approach for determining
the area of both types, separately.

How to Find the Area of a Regular Polygon


To determine the surface area of regular polygons
with n sides (where each side is represented as ‘s’), we use
the formula;
1
A  (p a )
2 Area of Regular Polygon

Where, p is the perimeter, a is the apothem and s is the polygon side.

Mat1-08-graphics2
147
G.A. El-Sheikh MATLAB: Introductory Course 148

Example:
Find the area of a regular polygon with perimeter of 44 cm and apothem length of 10 cm.
As we know,
Area (A) = ½ x p x a
here p = 44 cm and a = 10 cm
 A = ½ x 44 x 10 cm2 = 220 cm2

Finding the area of regular polygon when the SIDE and APOTHEM are known.

Example:
Calculate the area of a regular pentagon with side 12 cm and apothem of 7.5 cm.

As the polygon is a pentagon having five sides, where each side (s) measures 12 cm, its
perimeter (p) is = (5 x s) = (5 x 12) = 60 cm
Now,
Area (A) = ½ x p x a
here p = 60 cm and a = 7.5 cm
 A = ½ x 60 x 7.5 cm2 = 225 cm2

How to Find the Area of an Irregular Polygon


For irregular polygons, we divide the polygon
into two or more regular polygons, find the
individual area of each such polygon, and then
add them to get the area of the total figure.

Mat1-08-graphics2
148
G.A. El-Sheikh MATLAB: Introductory Course 149

Finding the Area of Some Common and Basic Polygons


If we are looking to find the area of other basic polygons such as triangle, rectangle,
parallelogram, rhombus, trapezoid, kite, pentagon, and hexagon, we can also use their
standard formulas that are given below:

Area of Polygons
Finding the Area of a Polygon Given on a Coordinate Plane
For determining the area of a polygon given on a coordinate plane, we will use the following
formula:
Area (A) = | (x1y2 – y1x2) + (x2y3 – y2x3)…. + (xny1 – ynx1)/2 |

Mat1-08-graphics2
149
G.A. El-Sheikh MATLAB: Introductory Course 150

Area of a polygon (Coordinate Geometry)


First, number the vertices in order, going either
clockwise or counter-clockwise, starting at any
vertex.

The area is then given by the formula


( x y  y1 x 2 )  ( x 2 y 3  y 2 x 3 )  .......  ( x n y1  y n x 1 )
A 1 2
2
Where xn is the x-coordinate of vertex n, yn is the y-coordinate of the nth vertex etc.

The vertical bars mean you should make the reult positive even if it calculates out as negative.
Notice that the in the last term, the expression wraps around back to the first vertex again.

Adjust the quadrilateral ABCD by dragging any vertex. The area is calculated using this
method as you drag. A detailed explanation follows the diagram.

The above diagram shows how to do this manually;


1. Make a table with the x,y coordinates of each vertex. Start at any vertex and go around the
polygon in either direction. Add the starting vertex again at the end. You should get a
table that looks like the leftmost gray box in the figure above.
2. Combine the first two rows by:
1. Multiplying the first row x by the second row y. (red)
2. Multiplying the first row y by the second row x (blue)
3. Subtract the second product form the first.
3. Repeat this for rows 2 and 3, then rows 3 and 4 and so on.
4. Add these results, make it positive if required, and divide by two.

Mat1-08-graphics2
150
G.A. El-Sheikh MATLAB: Introductory Course 151

How to Find the Area of Regular Polygons


A regular polygon is a 2-dimensional convex figure with congruent sides and angles equal in
measure. Many polygons, such as quadrilaterals or triangles have simple formulas for finding
their areas, but if you're working with a polygon that has more than four sides, then your best
bet may be to use a formula that uses the shape's apothem and perimeter. With a little bit of
effort, you can find the area of regular polygons in just a few minutes.

1- Calculate the perimeter: The perimeter


is the combined length of the outline of
any two-dimensional figure. For a
regular polygon, it can be calculated by
multiplying the length of one side by the
number of sides (n).

2- Determine the apothem: The apothem of a regular polygon is the shortest distance from
the center point to one of the sides, creating a right angle. This is a little trickier to
calculate than the perimeter. The formula for calculating the length of the apothem is this:
the length of the side (s) divided by 2 times the tangent (tan) of 180 degrees divided by
the number of sides (n).

Thus,

Mat1-08-graphics2
151
G.A. El-Sheikh MATLAB: Introductory Course 152

3- Know the correct formula: The area of any regular polygon is given by the formula:
Area = (a x p)/2, where a is the length of the apothem and p is the perimeter of the
polygon.

4- Plug the values of a and p in the formula and get the area. As an example, let's use a
hexagon (6 sides) with a side (s) length of 10;
 The perimeter is 6 x 10 (n x s), equal to 60 (so p = 60).
 The apothem is calculated by its own formula, by plugging in 6 and 10 for n and s.
The result of 2tan(180/6) is 1.1547, and then 10 divided by 1.1547 is equal to 8.66.
 The area of the polygon is Area = a x p / 2, or 8.66 multiplied by 60 divided by 2. The
solution is an area of 259.8 units.
 Note as well, there are no parenthesis in the "Area" equation, so 8.66 divided by 2
multiplied by 60, will give you the same result, just as 60 divided by 2 multiplied by
8.66 will give you the same result.

Mat1-08-graphics2
152
G.A. El-Sheikh MATLAB: Introductory Course 153

Understanding the Concepts in a Different Way

1- Understand that a regular polygon can be thought of


as a collection of triangles: Each side represents the
base of a triangle, and there are as many triangles in
the polygon as there are sides. Each of the triangles
are equal in base length, height, and area.

2- Remember the formula for the area of a triangle: The area of any triangle is 1/2 times
the length of the base
(which, in the polygon, is
the length of a side)
multiplied by the height
(which is the same as the
apothem in regular
polygon).

Mat1-08-graphics2
153
G.A. El-Sheikh MATLAB: Introductory Course 154

3- See the similarities: Again, the formula for a regular polygon is 1/2 times the apothem
multiplied by the perimeter. The perimeter is just the length of one side multiplied the by
the number of sides (n); for a regular polygon, n also represents the number of triangles
that make up the figure. The formula, then, is nothing more than the area of a triangle
multiplied by the number of triangles in the polygon.

Mat1-08-graphics2
154
G.A. El-Sheikh MATLAB: Introductory Course 155

Perimeter and Area of Regular Polygons - From Triangles to Circles;


The Iso-Perimetric Theorem
The Iso-Perimetric Theorem (IP Theorem; iso - same perimeter) concerns with the relation
between the perimeter and the area of two dimensional (2-D) surfaces - plane figures.

IP Theorem may be stated as follows:


a. Among all 2-D shapes with the same perimeter, a circle has the largest area; or
equivalently; Among all 2-D shapes with the same area, a circle has the shortest perimeter.

For polygons (2-D shapes with n sides; n ≥ 3), IP Theorem may be stated as:

b. For an n-sided polygon (fixed n; n-gon) with the same perimeter, the regular polygon (all
sides of the same length) has the largest area.

c. Among all regular polygons (any n) with the same perimeter, the one with the largest
number of sides (largest n) has the largest area.

A circle may be considered a regular polygon approaching infinite number of sides and has
the largest area for a given perimeter (points b and c). Statement c is thus equivalent to
statement a of the theorem.

A corollary of the IP Theorem may be stated as

d. For a regular polygon for arbitrary n, the ratio of its area to its perimeter is equal to half
the radius of the inner circle (half its apothem).

About Polygons: The following two slides list the properties of regular polygons. They
relate the area and perimeter of n-sided polygons to their basic parameters like side length,
circumradius and the apothem. Centre of a regular polygon is the point that is equidistant
from all vertices of the polygon; it is the centre of the circumcircle.

Mat1-08-graphics2
155
G.A. El-Sheikh MATLAB: Introductory Course 156

Eq. 7 gives us the ratio of the area A to the perimeter of a regular polygon. For a given
parameter P, the maximum value the ratio (A/P) may have, is r/2 and that is for a circle for
which n tends to infinity and cos (/n) = 1. For all other values of n, area A of the polygon is
less than Pr/2.

We can make an interesting observation, from the graph on this slide: The ratio of the area
and the perimeter of a regular polygon equals to half the length of the inner circle radius (the
apothem). This result is independent of the number of sides in the polygon. Length of the
apothem y does increase with n according to eqns. 1 and 2; namely y = r cos(/n).

Mat1-08-graphics2
156
G.A. El-Sheikh MATLAB: Introductory Course 157

We also notice that the circle has the largest area for a given perimeter (A/P approaches 0.5 r
as n tends to infinity).

Regular n-gons have the largest area for a given perimeter: To understand this, we use a
heuristic approach and look at triangles formed on a chord in a circle with the vertices of the
triangles on the circumference.

Mat1-08-graphics2
157
G.A. El-Sheikh MATLAB: Introductory Course 158

The Equilateral Triangle: We shall use algebra to show that for a triangle (n = 3), for a
given perimeter an equilateral triangle has the largest area.

Mat1-08-graphics2
158
G.A. El-Sheikh MATLAB: Introductory Course 159

The Square: First we look at the general four-sided polygon (a quadrilateral) and show that
the rectangle (all internal angles equal to 90 degrees) has the largest area for a given
perimeter. Then we use the AM-GM theorem (the arithmetic mean of a set of numbers is
always greater than or equal to their geometric mean) to show that of all rectangles, a square
(a regular 4-gon; all sides are equal and angles = 90 degrees) has the largest area.

Mat1-08-graphics2
159
G.A. El-Sheikh MATLAB: Introductory Course 160

An interesting historical remark is that the formula K = (a+c)/2 x (b+d)/2 was used by the
ancient Egyptians to calculate the area of a quadrilateral, but it’s only a good approximation
if the angles of the quadrilateral are close to being right angles. In all quadrilaterals but
rectangles the formula gives an overestimate of the area, which the tax collectors probably
didn’t mind!

AM-GM Theorem: I now show that the largest area for a rectangle is for a square when all
four sides are equal.

Mat1-08-graphics2
160
G.A. El-Sheikh MATLAB: Introductory Course 161

Notes:
We considered convex polygons in the discussion. For completeness, next slide is used to
explain the difference between a convex and a concave polygon.

2. I find the case when y = 2 very interesting and have prepared a slide to show the numbers
for some polygons; (refer to slides 1 and 2 for notations).

In a circle, the inner and circumradius are always the same.

Mat1-08-graphics2
161
G.A. El-Sheikh MATLAB: Introductory Course 162

8.11 Animations
An animation is just a combination of multiple plots shown one after the other, separated by a
time interval sufficiently small to create the illusion that they are continuously changing. We
begin with an animation of a small clock with second hand only. The important function we
need to know is drawnow.

The command drawnow forces MATLAB to flush the graphics at that instant. By default, if
MATLAB sees any plot command in the middle of the execution of a heavy computation, it
waits until the computations are done and then shows the graphics.

Since we need to see the plots at that instant in order for the animation to vary with time, we
can use the drawnow command, which forces MATLAB to show the graphic at that instant
only.

8.11.1 Clock Animation


We create 100 time frames using a for-loop.
In each frame, we plot the clock outer ring and the hand, but the position of the hand will
change at each frame. Since 100 frames shows a full cycle of the hand (1 minute), 1 frame
represents a time duration of 1/100 minutes or (2/100) angular rotation on the clock. At the
ith frame, the needle will be just a line between
  2i   2i 
[0, 0] to   cos  ,   sin  
  100   100 
where  is the length of the hand.

To create the animation, we would carry out the following steps:


1. Clear the frame
2. Increase the frame number
3. Plot the outer ring of the clock as a circle
4. Plot the line for the hand
5. Go to step 1 if the current frame number is less than 100

The MATLAB Program:


Clock Animation
%************************************ 1
%*** clockanimate01.m ***
0.8
%************************************
%*** Clock Animation *** 0.6
%************************************
0.4
clc
clear 0.2
close all
0

t1 = 0:0.01:2*pi; -0.2
rclock1 = 1; % Clock Radius -0.4
lneedle1 = 0.95; % Needle length
-0.6

for i1=1:100 -0.8


% Plot objects of the ith frame
hold off; -1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
x1 = rclock1*cos(t1);

Mat1-08-graphics3
162
G.A. El-Sheikh MATLAB: Introductory Course 163

y1 = rclock1*sin(t1);
plot(x1,y1,'b--', 'Linewidth',4); grid on
title('Clock Animation')
hold on;
x0 = 0.01*cos(t1);
y0 = 0.01*sin(t1);
plot(x0,y0,'k', 'Linewidth',5);
x2 = lneedle1*cos(-2*pi*i1/100);
y2 = lneedle1*sin(-2*pi*i1/100);
plot([0 x2], [0 y2], 'r','Linewidth',2);
drawnow;
end

The hold off command tells MATLAB to let the previous frame graphics be deleted when the
new frame is plotted.
The above code generates an animation with the clock needle making one circle around the
clock; See Fig. 10.1 for one frame of the whole animation. We can add other clock hands for
hours and minutes and use three nested for loops to create the complete clock.

8.11.2 Wave Animation/Motion


Consider the wave motion of a string ( 0  x  1) where the height of a particle located at x is
given by;
( t , x )  sin( t   k x )

Suppose we want to visualize the height of particles situated on the string with varying time
( 0  t  1). As done in the previous example, we first plot a single frame at time i and then
repeat it for all frames. At time i, the string looks like a sin wave,
i  sin( i  k x)
Where i  i  .
%************************************
%*** waveanimate00.m *** 0

%************************************ -0.1
%*** Wave Animation *** -0.2
%************************************
-0.3
clc
clear -0.4

close all -0.5

-0.6
X1 = 0:0.01:1;
-0.7
k1 = 3;
-0.8
w1 = 100;
i1 = 0; -0.9

Wi = sin(-k1*X1 + i1*w1); -1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
plot(X1,Wi,'Linewidth',3);grid on

Now we iterate the code to plot for i = 0:0.1:10.


Here we are plotting only one object, so we don’t need to use hold on and therefore no
clearing of the figure is required.

Mat1-08-graphics3
163
G.A. El-Sheikh MATLAB: Introductory Course 164

%************************************
%*** waveanimate01.m ***
%************************************ 1
Wave Animation

%*** Wave Animation ***


0.8
%************************************
0.6
clc
clear 0.4

close all 0.2

X1 = 0:0.01:1.5; -0.2
k1 = 3; -0.4
w1 = 100;
-0.6

-0.8
for i1=0:0.001:1.5
W1 = sin(-k1*X1 + i1*w1); -1
0 0.5 1 1.5
W2 = cos(-k1*X1 + i1*w1);
plot(X1,W1,'b',X1,W2,'r','Linewidth',3);grid on
title('Wave Animation')
% legend('Sin','Cos',0)
drawnow;
end

Here the axis command fixes the axis so that at each plot the axis and hence the display frame
doesn’t move up and down.

Mat1-08-graphics3
164
G.A. El-Sheikh MATLAB: Introductory Course 165

8.11.3 Movies
We can also create a movie from an animation and save it to an AVI file.
Consider the previous example of the wave motion of a string. To create a movie frame from
the ith frame, we can use the get frame function in the following way;
%************************************
%*** movie02.m ***
%************************************
%*** Movies ***
%************************************
clc
clear
close all

X1 = 0:0.01:1;
k1 = 3;
w1 = 100;
j1 = 1;

for i1=0:0.001:1
W1 = sin(-k1*X1 + i1*w1);
plot(X1,W1,'b','Linewidth',3);grid on
title('Wave Movie')
drawnow;
M(j1) = getframe(gcf);
j1 = j1 + 1;
end

movie2avi(M,'moviename.avi');

Here gcf is the handle of the current figure and M is the matrix containing all frames. To
create the AVI movie containing these frames, we execute the following command;
movie2avi(M,'moviename.avi');

Mat1-08-graphics3
165
G.A. El-Sheikh MATLAB: Introductory Course 166

8.12 Simulation
In many cases, to understand the dynamics of a real world system or a function of a physical
system, we need to model it and imitate the step by step operation of the system using a
computational tool. This step by step imitation of a real world process is known as simulation.
The systems can include any physical phenomena such as Brownian motion or the path of a
projectile; or man-made devices such as robots or motors. Computational tools developed for
simulating a system can be based on hardware or software. In this chapter, we will learn how
to simulate in a software-based computation tool, in particular in MATLAB.

8.12.1 One Step Simulations


Although real world processes are infinite time processes, sometimes they can be regarded as
one time computations.

Example:
Suppose a projectile is thrown into the sky with velocity ( v x î  v y ĵ ) from the ground.
If we want to know the motion of this projectile or the range covered by it, even though the
process evolves with time, we can compute it in one step using motion equations:

Location path;
 
x(t )  v x t î  v y t  0.5 g t 2 ĵ
This can be plotted easily using the following code;
%************************************
%*** simulate01.m ***
%************************************
%*** Simulation: motion of a projectile ***
%************************************
clc
clear Trajectory of a projectile
25
close all
20
v1 = [10 20];
g1 = 9.8;
15
Vertical range [km]

%*** Flight time


tf1 = 2*v1(2)/g1; 10

%*** Range
r1 = v1(1)*tf1; 5

%*** Plot projectile path 0


t1 = [0:tf1/100:tf1];
x1 = v1(1)*t1;
-5
y1 = v1(2)*t1-0.5*g1*t1.^2; 0 5 10 15 20 25 30 35 40 45
Horizontal range [km]
plot(x1,y1,'linewidth',3); grid on
title('Trajectory of a projectile')
xlabel(' Horizontal range [km]')
ylabel(' Vertical range [km]')

Mat1-08-graphics3
166
G.A. El-Sheikh MATLAB: Introductory Course 167

However, when the motion is complex, e.g. affected by many forces or collisions, it is very
hard to compute the equations of the path. In such cases we need to simulate the process at
small time steps to see how each object moves in each instant. We will see how we can
simulate projectile motion using iterative simulations in later sections of this chapter.

In this section, we will consider a


simple example from optics which
will illustrate the basic technique
of one step simulation.

Let us assume a point located at x


= a, y = 0. A plane mirror is
positioned in the YZ plane at y=0.
To compute the reflection, we will
take two rays originating from the
point and find its reflected ray and
finally compute the intersection to
find the image (Fig. 8.12.2 shows Fig. 8.12.2: Ray tracing diagram for a point
the results). object in front of a plane mirror

%************************************
%*** simulate02.m ***
%************************************
%*** Simulation: ***
%************************************
clc
clear
close all

%Location of the point


a=10;x1=[a 0];
%take first line at theta =120, line in the format y=m1x+c1
t1=120;m1=tand(t1);
c1=0-m1*a;
%hitting point at mirror
A=[0 0*m1+c1];
%reflected light y=mr1x+cr1
mr1=tand(180-t1);cr1=A(2)- mr1*A(1);
%second ray at t=150
t2=150;m2=tand(t2);
c2=0-m2*a;B=[0 0*m2+c2];
mr2=tand(180-t2);cr2=B(2)- mr2*B(1);
%intersection of y=mr1x+cr1 and y=mr2x+cr2
xr=(cr2-cr1)/(mr1-mr2);
yr=xr*mr1+cr1;
disp([xr yr]);

Mat1-08-graphics3
167
G.A. El-Sheikh MATLAB: Introductory Course 168

8.12.2 Iterative Methods


First, as a warm up exercise, we discuss some numerical methods which require iterations to
be performed. Let us take a simple example of computing the zeros of the following equation:
f ( x )  x sin( x )  0.2  0
There are many techniques available to solve equations of the form f (x)=0.
One of them is the Newton-Raphson method, which is performed as follows:
1. We begin with a first guess x0.
2. A better solution of the equation x1, can be computed as
f (x 0 )
x1  x 0 
f ( x 0 )
3. Compute f (x1) and, if it is close enough to 0, terminate the algorithm and output x1.
4. Now put x0 = x1 and compute x1 again by returning to step 2.

The algorithm is terminated when f (x1) is close enough to zero, let us say when
f (x1 )   f
where  f is known as the function tolerance and can be arbitrarily defined according to the
precision required. In this example, we set it to be equal to 0.001. There can be other
termination conditions too, for example, we can terminate the algorithm when the value of x
varies by a small difference in two consecutive iterations, in other words if
x1  x 0   x
Here  x is known as the x tolerance. The tolerance can also be defined in relative rather than
absolute terms. For example, we can terminate the algorithm when,
x1  x 0
  x ,r
x0
Let us first define the function and its derivative along with some parameters.
f=@(x) x.*sin(x)-0.2;
fprime=@(x) sin(x)+x.*cos(x);
x_0=0.1;
tolerance=0.001;

To implement the algorithm, we will first implement a single step, computing x1 from x0;
x_1=x_0-f(x_0)/fprime(x_0);

Let us compute the error value of this step;


err_step=abs(f(x_1));

Note that if we were using the x tolerance, the err_step would be


err_step=abs(x_1-x_0);

Now for the next step, we need to assign the value of x0 to x1 so that the previous line of code
can be used again for the next step when computing the next x1.
x_0=x_1;

The whole step will look like


x_1=x_0-f(x_0)/fprime(x_0);
err_step=abs(f(x_1));
x_0=x_1;

Now this step can be repeated until the tolerance condition is met. The final value of x1 will
be the solution. The whole code would look like the following;

Mat1-08-graphics3
168
G.A. El-Sheikh MATLAB: Introductory Course 169

%************************************
%*** simulate03.m ***
%************************************
%*** Simulation: ***
%************************************
clc
clear
close all

f1 = @(x) x.*sin(x)-0.2;
f2 = @(x) sin(x)+x.*cos(x);

x0 = 0.1;
d1 = 0.001; % Tolerance
E1 = 100; % error_step

while(E1>d1)
x1 = x0 - f1(x0)/f2(x0);
E1 = abs(f1(x1));
x0 = x1; Xsol=
0.4551
end
>>
Xsol = x1

When we run the above code, we get the answer as 0.4551.

8.12.3 Simulation of Real World Processes


In the previous section, we have seen how to implement an iterative method. Most real world
processes are finite or infinite iterations of some steps. Let us first concentrate on discrete
processes.

Discrete Processes
A discrete process x[n] is generally represented in the following two forms:
1. Explicit expression of the value of the process at time n as x[n]. For example: x[n]=
sin(2pn).
2. Definition of x[n] in terms of values at previous time steps, known as a time update
equation. For example: x[n ]  0.5x[n  1]  w[n ] .

We will concentrate on the second definition as the first one is trivial. The following are the
important steps used to simulate any real world process;
1. Understand the process and make a mathematical model to compute the time step
update equation.
2. Model/generate or acquire the input signal.
3. Implement one time step.
4. Repeat the iterations for the desired time duration.

The following subsections discuss some examples of discrete random processes.

Mat1-08-graphics3
169
G.A. El-Sheikh MATLAB: Introductory Course 170

Random Walks
A random walk is a walk or series of steps where each step taken by the object is independent
of all previous steps. It is also known as a drunken walk, where the person does not know
where to go and each step taken by him is random. We will consider the discrete case in 2D
space where four possible steps are allowed:
1. [ 1 0] : unit step in the direction of the positive X axis
2. [-1 0] : unit step in the direction of the negative X axis
3. [ 0 1] : unit step in the direction of the positive Y axis
4. [ 0 -1] : unit step in the direction of the negative Y axis

At each time step, the object chooses a number randomly out of {1,2,3,4} and depending on
that number, it will take a step in the corresponding direction. A similar process is followed at
each time step and this continues indefinitely. The random walk is the basis of many natural
processes, such as Brownian motion.

The update equation is given as;


r[n ]  r[n  1]  [10] w[ n ] 4  [10] w[ n ]1  [01] w[ n ] 2  [0  1] w[ n ]0
Here r[n] is the location of the point at time step n;
r[n]  x[n], y[n]

and w[n] is a random number with value between 1 to 4.

Since it is an iterative process, we will need to use a loop for its simulation. We will first
simulate a single step, then we will put a loop around it. A single time step at time n consists
of the following four sub-steps;
1. Assign the current position.
2. Generate a random number w[n] to select the direction of motion, which requires two bits
[w1, w2] of a random Bernoulli variable. These two values combined will select the
direction as follows:
b=rand(1,2);
w=b>0.5;
if w==1
rstep=[1 0];
elseif w(1)==1
rstep=[0 1];
elseif w(2)==1
rstep=[-1 0];
else
rstep=[0 -1];
end

Remember if you put w==1 as a condition inside the if-statement, it will be considered true
only when all the elements in b satisfy the condition.
3. Update the position with this new value:
rnew=r+rstep;

After we are done with one time step, we can put a loop around it to make it an iterative
process and let it run for, let us say, 1000 time steps. We initialize r as the origin before the
first time step.

Mat1-08-graphics3
170
G.A. El-Sheikh MATLAB: Introductory Course 171

r=[0 0];
for t= 0:0.1:100
b=rand(1,2);
w=b>0.5;
if w==1
rstep=[1 0];
elseif w(1)==1
rstep=[0 1];
elseif w(2)==1
rstep=[-1 0];
else
rstep=[0 -1];
end
rnew=r+rstep;
r=rnew;
end

Animation of the walk


Using the animation techniques learnt in previous chapters, we can also visualize the random
walk by plotting each step as a line connecting the previous location to the new one;
plot([r(1) rnew(1)],[r(2) rnew(2)]);

Since we are adding each step to the previous trace, we need to use hold on at least once so
that the previous steps are not deleted;
hold on;
plot([r(1) rnew(1)],[r(2) rnew(2)]);
drawnow

When we run this code, we will get Fig. 8.12.3. We can increase the time limit by changing
the for loop time vector.

%**********************************
%*** simulate04.m *** Simulation of a random walk
15
%**********************************
%*** Simulation: *** 10
%**********************************
clc 5
clear
close all 0

r = [0 0]; -5

for t= 0:0.1:100
-10
b = rand(1,2);
w = b>0.5;
-15
if w==1
rstep=[1 0]; -20
elseif w(1)==1 -30 -25 -20 -15 -10 -5 0 5 10 15 20

rstep=[0 1];

Mat1-08-graphics3
171
G.A. El-Sheikh MATLAB: Introductory Course 172

elseif w(2)==1
rstep=[-1 0];
else
Simulation of a random walk
rstep=[0 -1]; 5
end
rnew = r + rstep; 0
r = rnew;
hold on; -5
plot([r(1) rnew(1)],[r(2) rnew(2)],'ro',...
'linewidth',3,'MarkerSize',3); grid on
-10
title('Simulation of a random walk')
drawnow
-15
end
-20

-25
-15 -10 -5 0 5 10 15 20

8.12.4 Simulation of Continuous Time Processes


A continuous time process x(t) can again be represented mainly in two ways:
1. Explicit form, for example,
x(t )  t sin( t  )  e  t cos( t )  (t )
2. Time update equations
Here the rate of change of the process describes its dynamics. For example, consider a
process x(t) defined by
x ( t )  cos( t )  2e  t  0.4  (t )
where w(t) is the input signal.

The first form is trivial, as before, so we concentrate on the second form. The first task when
simulating such systems is to convert the system to a discrete time system via the following
steps:
1. Fix a sample time interval d and sample the system with time step d
t  t0   n
where t0 is the start of the world, typically taken as 0.
2. Next replace the derivate terms by the first principle definition of differentiation
dx ( t ) x ( t  )  x ( t )

dt 

Thus, using the sample time definition, x ( t  ) can be written as


x(t  )  x(t 0   n  )  x[n  1]

Let us work on the above mentioned example. The time update equation can be written as;

Mat1-08-graphics3
172
G.A. El-Sheikh MATLAB: Introductory Course 173

x ( t  )  x ( t )
 cos( t )  2e  t  0.4  ( t )

x[n  1]  x[n ]
  cos(n )  2e n  0.4  [n ]


 x[n  1]  x[n ]   cos(n )  2e n  0.4  [n ] 
which is in the same format as the discrete system discussed in the previous section and can
be simulated in a similar way. We can actually save the whole process with respect to time
instead of just keeping the current value. Recall that, in the previous example, at each step we
updated r to rnew. At the end of the simulation, you don’t have access to the locations at
previous times. In the following code, we will save all the values in a matrix x where the nth
element of the matrix represents x[n]. We also assume that the input w(t) is zero.

%************************************ Simulation of a continuous time process


%*** simulate05.m *** 9

%************************************ 8
%*** Simulation: motion of a projectile
7
***
%************************************ 6

clc 5
clear
4
close all
3
n1 = 1:150;
2
x1(1) = 0;
delta1 = 0.1; 1

for i1= 1:length(n1)-1 0


0 50 100 150
x1(i1+1) = x1(i1)+delta1*(cos(delta1*i1)+... Sample
2*exp(-delta1*i1)+0.4);
end
plot(n1,x1,'r-','linewidth',3); grid on
title('Simulation of a continuous time process')
xlabel('Sample')

Let us now see how we can compute the motion of a projectile as discussed in the first
section. At any time step, the update in velocity is given as;
v x [n  1]  v x [n ]
v y [n  1]  v y [n ]  g 

and the location is updated as;


x x [n  1]  x x [n ]  v x [n ] 
x y [n  1]  x y [n ]  v y [n ] 

The simulation should terminate when the ball hits the ground, i.e. when xy is less than zero.
%************************************
%*** simulate06.m ***
%************************************

Mat1-08-graphics3
173
G.A. El-Sheikh MATLAB: Introductory Course 174

%*** Simulation: motion of a projectile ***


%************************************
clc
clear
close all

v1 = [10 20];
g1 = 9.8;
x1 = [0 0];
delta1 = 0.01;
t1 = 0;
while (x1(2)>=0)
v1 = v1 + [0 -g1*delta1];
x1 = x1 + v1*delta1;
plot(x1(1),x1(2),'ro','linewidth',2,'MarkerSize',3); grid on
title('Motion of a projectile')
hold on; Motion of a projectile
axis([0 45 0 25]) 25
drawnow;
t1 = t1 + delta1;
end 20
tf1 = t1; % flighttime
Rm1 = x1(1); % Horizontal range
15

10

0
0 5 10 15 20 25 30 35 40 45

8.12.5 Balls in a 2D Box


Consider a somehow complex example; suppose there are N balls in a 2D plane, given initial
velocities and confined within some boundary (-Lx, yL). As the balls move in a plane, if
they collide with other balls, they exchange their velocities and continue moving. If they hit
the boundary, they reverse their component of velocity, which is in the direction of
confinement. For example, if they hit x=L, their velocity will change as,
vx   v x
vy  v y
We are interested in simulating this system for two minutes with a time interval of 0.1sec,
which corresponds to 1200 time step evaluations as;
T 120
Nt    1200
 0.1

Mat1-08-graphics3
174
G.A. El-Sheikh MATLAB: Introductory Course 175

To simulate this, we follow the same procedure.


First, let us fix the notation we are going to use in the MATLAB code;
 The x location of the ith ball at time n is going to be stored as bx(i,n).
 Similarly, store the y location of the ith ball in by(i,n),
 The x component of the velocity of ball i at step n is stored in vx(i,n) and
 The y component in vy(i,n).
Let us see what happens to a particular ball at time step n given the x locations and velocities
of all balls at time step n.

1. Determine if the ball is hitting any other ball. A hit occurs if the distance between two balls
is less than the sum of their radii. Let us assume that a ball can hit only one ball at any
time, so if more than one ball satisfies the distance criteria, we will just take the closest of
all such balls. If such a collision occurs, we set hit equal to 1.

Dis=(bx(i, n)-bx([1:i-1 i+1:end],n]).^2...


+(by(i, n)-by([1:i-1 i+1:end],n]).^2;
[closestDistance closestBall]=min(Dis);
%since we are now counting i, adjust the index of the closest ball
% to reflect the true index
if closestBall>i-1
closestBall=closestBall+1;
end
if closestDistance<(2*r)^2
hit=1;
end

2. Determine if the ball has hit the wall. It is a hit if the ball is outside the boundary. In this
case we set hit equal to 2.
if bx(i,n)>=L-r || bx(i,n)<=-L+r || by(i,n)>=L-r || by(i,n)<=-L+r
hit =2;
end

3. If there is a hit, update the velocity at n+1 for the ith ball accordingly.
if hit==1
vx(i,n+1)=vx(closestBall,n);
vy(i,n+1)=vy(closestBall,n);
elseif hit==2
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
if bx(i,n)>=L-r || bx(i,n)<=-L+r
vx(i,n+1)=-vx(i,n);
end
if by(i,n)>=L-r || by(i,n)<=-L+r
vy(i,n+1)=-vy(i,n);
end
else
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
end

Mat1-08-graphics3
175
G.A. El-Sheikh MATLAB: Introductory Course 176

4. Update the location for n+1 using the velocity at n+1.


bx(i,n+1)=bx(i,n)+delta*vx(i,n+1);
by(i,n+1)=by(i,n)+delta*vy(i,n+1);

Having carried out all the above steps, we obtain the velocity and location of ball i for time
step n+1. Now we need to do the above for all the balls and then repeat it for each time step.
Animation
Now we can visualize the motion of the balls by plotting each individual ball as a circle inside
the 2D boundary. The following code does the same:
clf; %clear the figure
%plot the boundary
plot([L –L –L L L],[L L –L –L L],'LineWidth',3);
hold on;
%create x and y for plotting a circle
theta=0:.1:2*pi;x=r*cos(theta);y=r*sin(theta);
%loop for all the balls
for i=1:N
plot(bx(i,n)+x,by(i,n)+y,'LineWidth',4);
end
axis([-L-5 L+5 -L-5 L+5])
drawnow

The complete code will look something like the following:

%************************************
%*** simulate07.m ***
%************************************
%*** Simulation: Balls in a 2D Box ***
%************************************
clc
clear
close all

delta = 0.1;
r = 0.2;
n = 0;
N = 7;
L = 10;

%*** Initilialize
bx = L*(rand(N,1)-0.5);
by = L*(rand(N,1)-0.5);
vx = 4*(rand(N,1)-0.5);
vy = 4*(rand(N,1)-0.5);

%*** Colors of balls


c='rgbcmyk'; % red-green-blue-cayan-magneta-yellow-black

for t=0:delta:120
n = n + 1;

Mat1-08-graphics3
176
G.A. El-Sheikh MATLAB: Introductory Course 177

for i=1:N
hit = 0;
%*** Computing the hits
Dis = (bx(i, n)-bx([1:i-1 i+1:end],n)).^2 ...
+(by(i, n)-by([1:i-1 i+1:end],n)).^2;
[closestDistance closestBall]=min(Dis);
if closestBall>i-1
closestBall = closestBall + 1;
end
if closestDistance<(2*r)^2
hit = 1;
end
if bx(i,n)>=L-r || bx(i,n)<=-L+r ...
|| by(i,n)>=L-r || by(i,n)<=-L+r
hit = 2;
end
%*** Updating velocities
if hit==1
vx(i,n+1) = vx(closestBall,n);
vy(i,n+1) = vy(closestBall,n);
elseif hit==2
vx(i,n+1) = vx(i,n);
vy(i,n+1) = vy(i,n);
if bx(i,n)>=L-r || bx(i,n)<=-L+r
vx(i,n+1) = -vx(i,n);
end
if by(i,n)>=L-r || by(i,n)<=-L+r
vy(i,n+1) = -vy(i,n);
end
else
vx(i,n+1) = vx(i,n);
vy(i,n+1) = vy(i,n);
end
%*** Updating the locations
bx(i,n+1) = bx(i,n) + delta*vx(i,n+1);
by(i,n+1) = by(i,n) + delta*vy(i,n+1);
end

%*** Plotting
clf; %clear the figure
% *** Plot the boundary
plot([L -L -L L L],[L L -L -L L],...
'LineWidth',3); grid on
title('Simulation: Balls in a 2D Box')
hold on;
%*** Create x and y for plotting a circle
theta = 0:.1:2*pi;
x = 3*r*cos(theta);
y = 3*r*sin(theta);
%*** Loop for all the balls

Mat1-08-graphics3
177
G.A. El-Sheikh MATLAB: Introductory Course 178

for i=1:N
plot(bx(i,n)+x,by(i,n)+y,c(i),'LineWidth',10);
end
axis([-L-5 L+5 -L-5 L+5])
drawnow
end
The above code will result in an animation, one frame of which will look like Fig. 8.12.6.

Simulation: Balls in a 2D Box


15

10

-5

-10

-15
-15 -10 -5 0 5 10 15

The above simulation has some issues and can be refined. For example, after each update of
location, the locations can be checked for consistency so that no ball is beyond the boundary
and no two balls intersect each other. In that case, the velocities and locations can be updated
in the middle of the step by computing the time of hit and interpolating that way instead of
waiting for the next time step to update. Let us also analyze the effect of the time step. As we
decrease the time step, the simulation becomes more accurate as it is able to compute the hits
more accurately. We can observe the impact of d in the accuracy and continuity of the plots.

8.12.6 Motion in a Force Field


Let us assume that there are two force fields acting on each ball:
1. An electrical force field of E which exerts a force of (qE ) where q is the charge on each
ball. The acceleration caused at each ball is
qE
aE 
m
where m is the mass of each ball. We assume that odd numbered balls are positively
charged while even numbered balls are negatively charged.
q=1.6e-7*ones(N,1);q(2:2:end)=-1.6e-7;E=[1e6 0];m=1;
2. There is a continuous flow of wind which causes the balls to drift in the direction of the
wind, which applies acceleration equals to aw;

Mat1-08-graphics3
178
G.A. El-Sheikh MATLAB: Introductory Course 179

aw=[.02 .02];

These forces will add a (aw+aE) term to the velocity at each time step. The rest of the code
will be the same and only the updates of velocities will be modified as follows;
%updating velocities
if hit==1
vx(i,n+1)=vx(closestBall,n);
vy(i,n+1)=vy(closestBall,n);
elseif hit==2
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
if bx(i,n)>=L-r || bx(i,n)<=-L+r
vx(i,n+1)=-vx(i,n);
end
if by(i,n)>=L-r || by(i,n)<=-L+r
vy(i,n+1)=-vy(i,n);
end
else
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
end
vx(i,n+1)=vx(i,n+1)+q(i)*E(1)/m*delta+aw(1)*delta;
vy(i,n+1)=vy(i,n+1)+q(i)*E(2)/m*delta+aw(2)*delta;

Since there are drifts in the direction of the X axis, we need to verify the consistency of
location at the end of the full iteration;
%updating the locations
bx(i,n+1)=bx(i,n)+delta*vx(i,n+1);
by(i,n+1)=by(i,n)+delta*vy(i,n+1);
%check consistancy
if bx(i,n+1)>L-r
bx(i,n+1)=L-r;
end
if bx(i,n+1)<-L+r
bx(i,n+1)=-L+r;
end
if by(i,n+1)>L-r
by(i,n+1)=L-r;
end
if by(i,n+1)<-L+r
by(i,n+1)=-L+r;
end

Let us plot the x location of ball 1 and 2 (see Fig. 8.12.7).


plot((0:n)*delta,bx(1,:),'r','LineWidth',2)
hold on;
plot((0:n)*delta,bx(2,:),'g','LineWidth',2)

%************************************
%*** simulate08.m ***

Mat1-08-graphics3
179
G.A. El-Sheikh MATLAB: Introductory Course 180

%************************************
%*** Simulation: ***
%*** Balls Motion in a Force Field ***
%************************************
clc
clear
close all

delta = 0.1;
r = 0.2;
n = 0;
N = 7;
L = 10;

%*** Initilialize
bx = L*(rand(N,1)-0.5);
by = L*(rand(N,1)-0.5);
vx = 4*(rand(N,1)-0.5);
vy = 4*(rand(N,1)-0.5);

q=1.6e-7*ones(N,1);
q(2:2:end)=-1.6e-7;
E=[1e6 0];
m=0.1;
aw=[0.02 0.02];

%*** Colors of balls


c='rgbcmyk'; % red-green-blue-cayan-magneta-yellow-black

for t=0:delta:120
n = n + 1;
for i=1:N
hit = 0;
%*** Computing the hits
Dis = (bx(i, n)-bx([1:i-1 i+1:end],n)).^2 ...
+(by(i, n)-by([1:i-1 i+1:end],n)).^2;
[closestDistance closestBall]=min(Dis);
if closestBall>i-1
closestBall = closestBall + 1;
end
if closestDistance<(2*r)^2
hit = 1;
end
if bx(i,n)>=L-r || bx(i,n)<=-L+r ...
|| by(i,n)>=L-r || by(i,n)<=-L+r
hit = 2;
end
%*** Updating velocities
if hit==1
vx(i,n+1)=vx(closestBall,n);

Mat1-08-graphics3
180
G.A. El-Sheikh MATLAB: Introductory Course 181

vy(i,n+1)=vy(closestBall,n);
elseif hit==2
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
if bx(i,n)>=L-r || bx(i,n)<=-L+r
vx(i,n+1)=-vx(i,n);
end
if by(i,n)>=L-r || by(i,n)<=-L+r
vy(i,n+1)=-vy(i,n);
end
else
vx(i,n+1)=vx(i,n);
vy(i,n+1)=vy(i,n);
end
vx(i,n+1)=vx(i,n+1)+q(i)*E(1)/m*delta+aw(1)*delta;
vy(i,n+1)=vy(i,n+1)+q(i)*E(2)/m*delta+aw(2)*delta;

%*** Updating the locations


bx(i,n+1)=bx(i,n)+delta*vx(i,n+1);
Simulated path (x axis only) for balls 1 and 2 in force fields
by(i,n+1)=by(i,n)+delta*vy(i,n+1); 10
%check consistancy
8
if bx(i,n+1)>L-r
bx(i,n+1)=L-r; 6
end 4
if bx(i,n+1)<-L+r
2 Ball-1
bx(i,n+1)=-L+r; Ball-2
end 0
if by(i,n+1)>L-r
-2
by(i,n+1)=L-r;
end -4

if by(i,n+1)<-L+r -6
by(i,n+1)=-L+r;
-8
end
end -10
0 20 40 60 80 100 120 140

%*** Plotting
plot((0:n)*delta,bx(1,:),'r',...
(0:n)*delta,bx(2,:),'b','LineWidth',2), grid on
end
legend('Ball-1','Ball-2',0)
title('Simulated path (x axis only) for balls 1 and 2 in force fields')

Mat1-08-graphics3
181
G.A. El-Sheikh MATLAB: Introductory Course 182

8.12.7 Event-Based Simulations


We have seen how a continuous process can be converted to a discrete time process by
sampling it with equal sample intervals. However, sometimes, updates of states don’t happen
at equal intervals { n : n   } but instead these updates are determined by events
{ t n : n   }.

For example, in the example from the previous section, velocities need not be updated at each
sample time step, they are only updated after collisions with other balls and the wall. The
obvious benefit of an event-based simulation is that it reduces the computation time as the
events are sparse and there are significantly fewer events than time steps. Moreover, they
affect the accuracy of the simulations too.

For example, in the previous section, the collision may happen in the middle of the step. In
that case, the simulation has to wait for the next time step before updating the velocities and,
in this time, a ball will go inside the colliding ball in the simulation, which will never happen
in the real world. Event-based simulations require computations of the times when events will
happen well ahead of time and modeling the dynamics of the system to compute the updates
of states. Consider the following process:
d
x(t)  f (t)
dt
For a fixed interval simulation, x(t) is discretized as,
x[n ]  x (n)
and we can easily compute the x(t) at the next time step as,
x[n  1]  x[n ]  f (n) 

if  is small enough, whereas for the event-based simulation, x(t) is discretized as,
x[n]  x(t n )
and the value of x(t) at the next event needs to be computed as,
t n 1

x[n  1]  x[n ]   f (t)dt


tn

Let us take a simple example of a bouncing ball. Suppose a ball with elasticity constant e is
dropped at velocity 0 from height h. The ball hits the ground with some velocity v and
bounces back into the air with velocity v1b=-v. It then goes up and comes back again to hit the
ground with velocity v1e and bounces back with velocity v2b=-ev1e. From the symmetry of
flight we know that vib=vie for the ith bounce.

Here each bounce is an event. Note that the velocity and locations are still changing
continuously between events and we need to compute the ball’s motion until the next event
ahead of time at the previous event itself. We know that at the ith bounce, the location of the
ball is given by
h ( t )  v ib ( t  t i )  0.5 g ( t  t i ) 2
where ti is the start of the ith bounce. Let us simulate the system for n bounces as follows:

%************************************
%*** simulate09.m ***
%************************************
%*** Simulation: ***

Mat1-08-graphics3
182
G.A. El-Sheikh MATLAB: Introductory Course 183

%*** Simulated motion of a bouncing ball ***


%************************************
clc Simulated motion of a bouncing ball
20
clear
close all
15
u = 0;
g = 9.8;
H = 20; 10

Height of Ball
e = 0.7;
n = 10;
5

%*** Time until first bounce


T = sqrt(2*H/g); 0
v = -g*T;
vb(1) = -e*v;
t(1) = T; -5
0 2 4 6 8 10 12
tempt = 0:T/20:T; Time [sec]

temph = H + u*tempt - 0.5*g*(tempt).^2;


plot(tempt,temph,'b','Linewidth',3); grid on
title('Simulated motion of a bouncing ball')
xlabel('Time [sec]')
ylabel('Height of Ball')
hold on;

%*** Color for each bounce


c='rgbcmykrgbcmykrgbcmyk';

for i=1:n
ve(i) = -vb(i); %speed at the end of the ith bounce
vb(i+1)=-e*ve(i); %speed at the beginning of the i+1th bounce
ft(i) = 2*vb(i)/g; %flight time of ith bounce.
h(i) = 0.5*g*(ft(i)/2)^2; %height achieved in the ith bounce
t(i+1) = t(i)+ft(i); %start of the i+1 bounce
%computation for the ith bounce
tempt = t(i):ft(i)/20:t(i+1);
temph = vb(i)*(tempt-t(i)) - 0.5*g*((tempt-t(i))).^2;
%plot the ith bounce
plot(tempt,temph,c(i),'Linewidth',3);
end

Mat1-08-graphics3
183
G.A. El-Sheikh MATLAB: Introductory Course 184

8.12.8 Monte Carlo Simulations


Most real world processes have some random components in them. That is why we have to
investigate the statistical properties of such systems/processes. For example, we may be
interested in computing the expected performance of a system or the expected distance in a
random walk process, or the mean power of a received signal or the expected number of
people in a waiting room. Many mathematical tools have been derived to compute such
metrics, however in most cases the systems are too complex to derive any tractable results. In
such scenarios, simulations with random sampling, also known as Monte Carlo simulations,
can provide the desired analysis. This technique is based on the assumption that if we perform
random sampling of a random variable sufficiently many times, we can derive the
approximate statistical properties of it. On the other hand, we sometimes add the random
component into a computation or algorithm deliberately when deterministic computation is
very extensive or difficult. Monte Carlo simulations are also very useful in such cases.

Random Sampling
In this section, we will discuss the basic concept behind Monte Carlo simulation and see why
it achieves the almost correct solution. Let us start with a simple example of computing the
third moment of a Gaussian random variable.

The Third Moment of a Gaussian Random Variable


Suppose X is a Gaussian random variable with mean m and variance s. Suppose we want to
compute the third moment of such a random variable. We know that the distribution of a
Gaussian random variable is given by,
1 ( x m)2
1 
f (x)  e 2 s

2s
and the third moment is given by,

E[ x 3 ]   x f (x)dx
3


which we can compute via the following code;
h=.01;
m=1;
s=1;
x=-10:h:10+m;
y=x.^3.*1/sqrt(2*pi*s)*exp(-0.5*(x-m).^2/s);
mom3_int=trapz(x,y);

Here the accuracy of the code is dependent on the value of h and the range of computation
(which is -10:10 here). Let us see how we can compute the third moment using Monte Carlo
simulation. We know that the sample third moment is given by;
1 N
E[ x 3 ]   x 3n
N n 1
where x is sampled from the given distribution X ~ N(m,s). The following code implements
the above computation:
N=10000;
x=m+sqrt(s)*randn(N,1);
mom3_sam=sum(x.^3)/N;

Mat1-08-graphics3
184
G.A. El-Sheikh MATLAB: Introductory Course 185

Here the accuracy is given by the value of N. As we increase N, the error drops as 1/ N . We
compare the values of both terms (mom3_int=4, mom3_sam=4.04). The latter simulation is
known as a Monte Carlo simulation because random sampling is used to compute the metric.

Moments of Random Processes


Similarly we can compute the statistical properties of any random process. Consider the
following random process
y( t )  sin( t  )  ( t )
where w(t) is the additive Gaussian random noise with unit variance and zero mean and ϕ is a
uniform random variable U[0,2]. Suppose that we are interested in finding the mean E[y(t)]
of this process at time t = t0. There are three approaches to solving this problem.

Sampling Realizations of the Process


We can generate multiple realizations of the process and collect one sample y(t) from each
realization at some fixed time t = t0 and then compute the mean of all these samples;
t0=4;sampletime=0.01;t=0:sampletime:10;
for i=1:1000
phi=rand(1)*pi*2;
w=randn(size(t));
y=sin(t+phi)+w;
samplesyatt0(i)=y(t0/sampletime+1);
end
meanatt0=mean(samplesyatt0);

Time Averaging
Since we know that the process is stationary and ergodic, E[y(t)] will be independent of the
time t and can also be computed using time averaging by the following equation;
T
1
E[ y( t )]   y( t )dt
T0

t0=4;
sampletime=0.01;
t=0:sampletime:10;
phi=rand(1)*pi*2;
w=randn(size(t));
y=sin(t+phi)+w;
meanatt=1/10*trapz(t,y);

Time Sampling
We can also compute the mean of x(t) by taking samples of just one realization of the process
at uniform time intervals and then computing the mean of all these samples.
t0=4;sampletime=0.01;t=0:sampletime:10;
phi=rand(1)*pi*2;
w=randn(size(t));
y=sin(t+phi)+w;
meanatt=mean(y);

Mat1-08-graphics3
185
G.A. El-Sheikh MATLAB: Introductory Course 186

Sampling from a Given Distribution


We will see that almost all the methods used in this chapter will need random values
generated from some given distribution in order to compute results. Therefore it is essential to
first learn how we can sample a distribution to generate random values from it.

Inbuilt Functions
MATLAB provides inbuilt functions for the generation of random samples from many
standard distributions. Here are a few examples;

Uniform Distribution
U=rand(N,M);
%Generates an NxM vector of U(0,1)
U=a+(b-a)*rand(N,M);
%Generates an NxM vector of U(a,b)

Gaussian Distribution
X=randn(N,M);
%Generates an NxM vector of N(0,1)
X=m+sqrt(s)*rand(N,M);
%Generates an NxM vector of N(m,s)

Exponential Distribution
X=exprnd(m,N,M);
%Generates NxM vector of Exp(m)

Bernoulli Distribution
p=0.3;
U=rand(N,M)<p;

8.12.9 Communication Channels


Monte Carlo simulation is widely used in communications to evaluate wireless systems. In
this section, we will discuss one specific channel model and see how we can compute its
performance using a Monte Carlo method.

Consider a transmitter (Tx)-receiver (Rx) pair where Tx transmits a signal x[n] which is a
Bernoulli random variable with p=0.5. The signal is received at Rx after being attenuated by
the channel according to the following equation;
y[n ]  h[n ] x[n ]  w[n ]
where h[n] is Rayleigh distributed and w[n] is Gaussian noise N(0,2). Let the decoder output
be x̂[ n ] . Since y[n] is a real value, the receiver decodes the original message by comparing
y[n] with 0 and decoding y[n] as 1 if y[n]0. An error happens if x̂[ n ] is not equal to y[n].
Our goal is to evaluate the average rate of error which is defined as the ratio between the total
number of errors and the total number of transmissions. This is also known as the probability
of error.

Mat1-08-graphics3
186
G.A. El-Sheikh MATLAB: Introductory Course 187

%************************************
%*** simcomm01.m ***
%************************************
%*** Simulation: ***
%*** Communication Channels ***
%************************************ Transmitted Signal
clc 1

clear 0.9

close all 0.8

0.7
N = 1000; 0.6
%generate the transmitted signal
0.5
x1 = rand(N,1)>0.5;
0.4

figure 0.3

plot(x1), grid on 0.2

title('Transmitted Signal') 0.1

0
0 100 200 300 400 500 600 700 800 900 1000
%channel
h1 = sqrt(sum(1/sqrt(2)*randn(N,2).^2,2)); Recieved Signal with noise
3.5
sigmasq = 0.1;
3
w1 = randn(N,1)*sqrt(sigmasq);
2.5

%add noise and fading 2

y1 = h1.*x1 + w1; 1.5

figure 0.5

plot(y1), grid on 0
title('Recieved Signal with noise') -0.5

-1
%decode
-1.5
yd1 = y1>0; 0 100 200 300 400 500 600 700 800 900 1000

e1 = abs(x1-yd1)>0;
ProbError = sum(e1)/N ProbError =
0.2560
>>

References
[1] Gupta, A.K., Numerical Methods using MATLAB, Springer Apress, 2014.
[2] Lindfield, G.R. and J.E.T. Penny, Numerical Methods using MATLAB, Third Edition,
Elsevier Inc. 2012.
[3] Lindfield, G.R. and J.E.T. Penny, Numerical Methods using MATLAB, Third Edition,
Elsevier Inc. 2019.
[4] Mathews, J.H. and K.D. Fink, Numerical Methods using MATLAB, 4th Edition, Pearson
Prentice Hall, 2004.
[5]

Mat1-08-graphics3
187
G.A. El-Sheikh MATLAB: Introductory Course 188

9- Dates and Times


MATLAB provides functions for time and date handling. These functions are in a directory
called timefun in the MATLAB Toolbox.

Category Function Description


Current date and time clock Current date and time as date vector
date Current date as date string
now Current date and time as serial date number
Conversion datenum Convert to serial date number
datestr Convert to string representation of date
datevec Date components
Utility calendar Calendar
datetick Date formatted tick labels
eomday End of month
weekday Day of the week
Timing cputime CPU time in seconds
etime Elapsed time
tic, toc Stopwatch timer

9.1 Date Formats


Types of Date Formats
MATLAB works with three different date formats: date strings, serial date numbers, and date
vectors. When dealing with dates you typically work with date strings (16-Sep-1996).
MATLAB works internally with serial date numbers (729284). A serial date represents a
calendar date as the number of days that has passed since a fixed base date. In MATLAB,
serial date number 1 is January 1, 0000. MATLAB also uses serial time to represent fractions
of days beginning at midnight; for example, 6 p.m. equals 0.75 serial days. So the string '16-
Sep-1996, 6:00 pm' in MATLAB is date number 729284.75.

All functions that require dates accept either date strings or serial date numbers. If you are
dealing with a few dates at the MATLAB command-line level, date strings are more
convenient. If you are using functions that handle large numbers of dates or doing extensive
calculations with dates, you will get better performance if you use date numbers. Date vectors
are an internal format for some MATLAB functions; you do not typically use them in
calculations. A date vector contains the elements [year month day hour minute second].
MATLAB provides functions that convert date strings to serial date numbers, and vice versa.
Dates can also be converted to date vectors.

Mat1-09-dates
188
G.A. El-Sheikh MATLAB: Introductory Course 189

Here are examples of the three date formats used by MATLAB.


Date Format Example
Date string 02-Oct-1996
Serial date number 729300
Date vector 1996 10 2 0 0 0

Conversions between Date Formats


Functions that convert between date formats are shown below.
Function Description
datenum Convert date string to serial date number
datestr Convert serial date number to date string
datevec Split date number or date string into individual date elements

Here are some examples of conversions from one date format to another.
d1 = datenum('02-Oct-1996')

d1 =
729300

d2 = datestr(d1+10)

d2 =
12-Oct-1996

dv1 = datevec(d1)

dv1 =
1996 10 2 0 0 0

dv2 = datevec(d2)

dv2 =
1996 12 2 0 0 0

Date String Formats


The datenum function is important for doing date calculations efficiently. datenum takes an
input string in any of several formats, with 'dd-mmm-yyyy', 'mm/dd/yyyy', or 'dd-mmm-
yyyy, hh:mm:ss.ss' most common. You can form up to six fields from letters and digits
separated by any other characters:
 The day field is an integer from 1 to 31.
 The month field is either an integer from 1 to 12 or an alphabetic string with at least
three characters.
 The year field is a non-negative integer: if only two digits are specified, then a year
19yy is assumed; if the year is omitted, then the current year is used as a default.
 The hours, minutes, and seconds fields are optional. They are integers separated by
colons or followed by 'AM' or 'PM'.
For example, if the current year is 1996, then these are all equivalent
'17-May-1996'
'17-May-96'

Mat1-09-dates
189
G.A. El-Sheikh MATLAB: Introductory Course 190

'17-May'
'May 17, 1996'
'5/17/96'
'5/17'
and both of these represent the same time
'17-May-1996, 18:30'
'5/17/96/6:30 pm'
Note that the default format for numbers-only input follows the American convention. Thus
3/6 is March 6, not June 3.
If you create a vector of input date strings, use a column vector and be sure all strings are the
same length. Fill in with spaces or zeros.

9.2 Output Formats


The function datestr(D,dateform) converts a serial date D to one of 19 different date string
output formats showing date, time, or both. The default output for dates is a day-month-year
string: 01-Mar-1996. You select an alternative output format by using the optional integer
argument dateform. This table shows the date string formats that corespond to each
dateform value.

dateform Format Description


0 01-Mar-1996 15:45:17 day-month-year hour:minute:second
1 01-Mar-1996 day-month-year
2 03/01/96 month/day/year
3 Mar month, three letters
4 M month, single letter
5 3 month
6 03/01 month/day
7 1 day of month
8 Wed day of week, three letters
9 W day of week, single letter
10 1996 year, four digits
11 96 year, two digits
12 Mar96 month year
13 15:45:17 hour:minute:second
14 03:45:17 PM hour:minute:second AM or PM
15 15:45 hour:minute
16 03:45 PM hour:minute AM or PM
17 Q1-96 calendar quarter-year
18 Q1 calendar quarter
Here are some examples of converting the date March 1, 1996 to various forms using the
datestr function.
d = '01-Mar-1999'

Mat1-09-dates
190
G.A. El-Sheikh MATLAB: Introductory Course 191

d =
01-Mar-1999

datestr(d)

ans =
01-Mar-1999

datestr(d, 2)

ans =
03/01/99

datestr(d, 17)

ans =
Q1-99

Current Date and Time


The function date returns a string for today's date.
date

ans =
02-Oct-1996
The function now returns the serial date number for the current date and time.
now

ans =
729300.71

datestr(now)

ans =
02-Oct-1996 16:56:16

datestr(floor(now))

ans =
02-Oct-1996

Mat1-09-dates
191
G.A. El-Sheikh MATLAB: Introductory Course 192

9.3 Calendar Calculation Problems


Key Concept
Let the day of the week to be found on a given date. To find that day we are going to use the
concept of odd days.

Odd Days:
In a given period, the number of days more than the complete weeks are called odd days.

Leap Year:
(i) Every year is divisible by 4 is a leap year, if it is not a century.
(ii) Every 4th century is a leap year and no other century is a leap year.

Examples:
Each of the years 1948, 2004, 1676 is a leap year
Each of the years 400, 1200, 1600, 2000 is a leap year
None of the years 100, 2001, 2005, 2100 is a leap year

Note:
A leap year has 366 days and the month February has 29 days.

Ordinary Year:
The year which is not a leap year is called an ordinary year. An ordinary year has 365 days
and the month February has 28 days.

Shortcut to find the no. of leap years in the given no. of years:
Divide the given number of years by 4 and take the integer part. That is the number of leap
years available in the given number of years.

Example:
Let us find the number of leap years in 75 years.
Divide 75 by 4.
That is,
75/4 = 18.75
In this, integer part is 18, which means that there are 18 leap years in 75 years.

Caution:
When we find the number of leap years in 100 years, we will divide 100 by 4 as explained
above.
Then,
100/4 = 25
Here, there are 25 numbers from 1 to 100 which are divisible by 25.
Even though 100 is divisible by 4, it is not leap year.
So, number of leap years in 100 years is
= 25 - 1
= 24

Mat1-09-dates
192
G.A. El-Sheikh MATLAB: Introductory Course 193

Counting of Odd Days:


(i) 1 leap year has 366 days = 52 weeks + 2 days.
So, 1 leap year has 2 odd days

(ii) 1 ordinary year = 365 days = 52 weeks + 1 day.


So, 1 ordinary year has 1 odd day

100 years = 76 ordinary years + 24 leap years


100 years = 76x1 + 24x2 = 76 + 48 = 124 days
100 years = 17 weeks + 5 days = 5 odd days
So, 100 years has 5 odd days

Number of odd days in 100 years = 5


Number of odd days in 200 years = 3
Number of odd days in 300 years = 1
Number of odd days in 400 years = 0
Similarly, each one of 800 years, 1200 years, 1600 years and 2000 years, etc, has 0 odd days.

Days of the week related to odd days:


0 odd days ---> Sunday
1 odd day ---> Monday
2 odd days ---> Tuesday
3 odd days ---> Wednesday
4 odd days ---> Thursday
5 odd days ---> Friday
6 odd days ---> Saturday

Problem-01:
What was the day of the week on 16th July,1776 ?
Solution:
16th July, 1776 :
= 1775 years + Period from 01.01.1776 to 16.07.1776
1775 :
= 1600 + 100 + 75
No.of odd days in 1600 years = 0 ----(1)
No.of odd days in 100 years = 5 ----(2)
No. of odd days in 75 years :
= 18 leap years + 57 ordinary years
= 18x2 + 57x1
= 93 days
= 13 weeks + 2 days
= 2 odd days ----(3)
From 01.01.1776 to 16.07.1776, we have,
Jan - 31 days
Feb - 29 days
Mar - 31 days
Apr - 30 days
May - 31 days
Jun - 30 days
July - 16 days

Mat1-09-dates
193
G.A. El-Sheikh MATLAB: Introductory Course 194

Total = 198 days


= 28 weeks + 2 days
= 2 odd days ----(4)
Add (1), (2), (3) and (4).
= 0+5+2+2
= 9 days
= 1 week + 2 days
= 2 odd days
2 odd days is corresponding to Tuesday
So, the day of the week on 16th July,1776 is Tuesday.

Problem-02:
On what dates of March 2005 did Friday fall ?
Solution:
First, we have to find the day on 01.03.2005.

01.03.2005:
= 2004 years + Period from 01.01.2005 to 01.03.2005
2004 :
= 2000 + 4
Number of odd days in 2000 years = 0 ----(1)
Number of odd days in 4 years :
= 1 leap year + 3 ordinary year
= 1x2 + 3x1
= 5 days ----(2)

From 01.01.2005 to 01.03.2005, we have,


Jan - 31 days
Feb - 28 days
Mar - 1 day
Total = 60 days.
= 8 weeks + 4 days
= 4 odd days ----(3)
Add (1), (2) and (3).
= 0+5+4
= 9 days
= 1 week + 2 days
= 2 odd days
2 odd days is corresponding to Tuesday.
That is, 01.03.2005 was Tuesday.
Then, Friday lies on 04.03.2005.
So, the dates of March, 2015 on which Fridays fell are
04, 11, 18 and 25

Problem-03:
For which of the following years, will the calendar for the year 2007 be the same ?
(a) 2014
(b) 2016
(c) 2017
(d) 2018

Mat1-09-dates
194
G.A. El-Sheikh MATLAB: Introductory Course 195

Solution:
For example, if our answer is 2018, we must have the same day on 01.01.07 & 01.01.18 and
number of odd days from 01.01.07 to 31.12.17 must be zero.
Let us check the same thing for each of the given options.

Option (a) 2015:


No. of odd days from 01.01.2007 to 31.12.2014 :
= 2 leap years + 6 ordinary years
= 2x2 + 6x1
= 10 days
= 1 week + 3 days
= 3 odd days [not correct]

Option (b) 2016:


No. of odd days from 01.01.2007 to 31.12.2015 :
= 2 leap years + 7 ordinary years
= 2x2 + 7x1
= 11 days
= 1 week + 4 days
= 4 odd days [not correct]

Option (c) 2017:


No. of odd days from 01.01.2007 to 31.12.2016 :
= 3 leap years + 7 ordinary years
= 3x2 + 7x1
= 13 days
= 1 weeks + 6 days
= 6 odd days [not correct]

Option (d) 2018:


No.of odd days from 01.01.2007 to 31.12.2017 :
= 3 leap years + 8 ordinary years
= 3x2 + 8x1
= 14 days
= 2 weeks + 0 day
= 0 odd day [correct]
So, Calendar for the year 2018 will be the same as for the year 2007.

Problem-04:
How many days are there in 'x' weeks 'x' days ?
Solution:
Number of days in 'x' weeks = 7x
Number of days in 'x' days = x
Number of days in 'x' weeks 'x'days :
= 7x + x
= 8x
So, the number of days in 'x' weeks x days is 8x.

Mat1-09-dates
195
G.A. El-Sheikh MATLAB: Introductory Course 196

Problem-05:
The last day of a century can not be
(a) Monday
(b) Tuesday
(c) Wednesday
(d) Thursday
Solution:
From the notes given on this web page, we have

Number of odd days in 100 years (1st century) = 5


So, the last day of 1st century is Friday.
Number of odd days in 200 years (2nd century) = 3
So, the last day of 2nd century is Wednesday.
Number of odd days in 300 years (3rd century) = 1
So, the last day of 3rd century is Monday

Number of odd days in 400 years (4th century) = 0


So, the last day of 4th century is Sunday

This pattern is repeated

Therefore, the last day of a century can not be Tuesday or Thursday or Saturday.

So, option (c) Tuesday is the correct answer.

How to find day of a date


Here is a method to convert between the Gregorian Calendar and the Julian Day Number.

Suppose the year, month, and date are given by (Y,M,D) where January and February are
included in the previous year, and March is month 00 of its year. Thus, January 1, 2000 would
be (1999,10,1). Then the Julian Day Number that starts at noon GMT on that day would be,
Y Y Y 153M  2
JDN  365Y      D  1721119
4 100 400 5

To get the day of the week (DOW) use


JDN+1≡DOW(mod7)

where
0=Sunday
1=Monday
2=Tuesday
3=Wednesday
4=Thursday
5=Friday
6=Saturday

The inversion of this process is a bit more complicated. To convert from JDN to (Y,M,D), use
the following:

Mat1-09-dates
196
G.A. El-Sheikh MATLAB: Introductory Course 197

Compute the number of days, modulo 7. Add the result to your present day.
For instance, today is Thursday, August 22, 2013.
August 23, 2014 is 366 days away;
366 ≡ 2 mod 7
so August 23, 2014 is a Saturday.

Computing the number of days between dates is tedious, but not difficult.

There is a very handy formula which, when memorized, will allow you to compute the day of
the week on which a date falls in your head. The formula for the 2000's is as follows:
1. Take the last two digits of the year, divide by four, disregard the remainder. Add the
quotient thus determined to the last two digits of the year.
2. Add a number for the month based on the following: January 1, February 4, March 4,
April 0, May 2, June 5, July 0, August 3, September 6, October 1, November 4,
December 6, except in a leap year, it is 0 for January and 3 for February.
3. Add the number of the month.
4. Add 6.
5. Divide the result by seven. The remainder indicates the day of the week. For example, if
the remainder is 3, the date falls on the third day of the week, or Tuesday. If the
remainder is 0, the date falls on the seventh day of the week, or Saturday.

Example:
Determine the day of the week on which September 30, 2017, falls.

17 divided by 4 equals 4, disregarding the remainder.


Adding 17 and 4 equals 21.
Add 6 for September gives us 27.

Mat1-09-dates
197
G.A. El-Sheikh MATLAB: Introductory Course 198

Adding 30 for the day gives us 57.


Adding 6 gives us 63.
63 divided by 7 is 9 with a remainder of zero.
Since the remainder is zero, September 30, 2017, falls on the seventh day of the week, or
Saturday, which is true.

This formula works for any date in the 2000's.


For the 1900's, omit Step 4.
For the 1800's, Step 4 should be "Add 2," and for the 1700's, it should be "Add 4," but bear in
mind that prior to September 14, 1752, Great Britain, including her American colonies,
observed the Julian Calendar.
Also, prior to 1750, the British calendar year began on March 25 and ended on the succeeding
March 24.
This formula is taken from the 1939 edition of Funk & Wagnall's College Standard Dictionary
(entry for the word "calendar").

Simple way to solve Calendar problems


In order to solve these types of problems you must know some codes;
 Year Code
 Month Code
 Day Code

Year Code:
1600-1699 6
1700-1799 4
1800-1899 2
1900-1999 0
2000-2099 6

Month Code:
Jan Feb Mar April May June July Aug Sep Oct Nov Dec
0 3 3 6 1 4 6 2 5 0 3 5

Day Code:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
0 1 2 3 4 5 6

Steps to solve:
Step 1: Add the day digit to last two digit of the year.
Step 2: Divide the last two digits of the year by four.
Step 3: Add the Quotient value in step 3 to result obtain in step 1.
Step 4: Add Month Code and year codes to the result obtain in step3.
Step 5: Divide the result of step4 by seven.
Step 6: Obtain the remainder and match with the day code.

Mat1-09-dates
198
G.A. El-Sheikh MATLAB: Introductory Course 199

Example:
What was the day on 23-04-1990?
Solution:

Algorithm on how to find the day of a week


In 1970, John Horton Conway came up with an algorithm, often termed the “Doomsday
Algorithm.” (Though it had no relation to December 21, 2012 — the predicted doomsday)

In 1970, John Horton Conway came up with an algorithm, often termed the “Doomsday
Algorithm.” (Though it had no relation to December 21, 2012 — the predicted doomsday) to
quickly calculate the day of a week without resorting to anything but a few calculations in
your head. (It is easy to memorize, so don’t fret.)

This algorithm uses the formula: (d+m+y+[y/4]+c ) mod 7


Where d is the day, m is the month addressed in the date, y is the calendar year, and c is the
century number.

Each day of the week is given a number. For instance, Sunday is the first day of the week and
is represented by 1, Monday by 2, and so on. In a few calendars, the week begins with 1 as for

Mat1-09-dates
199
G.A. El-Sheikh MATLAB: Introductory Course 200

Monday and 7 as Sunday, which is like the ISO 8601 standards calendar. These numbers are
achieved using Modulo 7.

What do we know?
We know that every year has 365 days (Except the leap year which has 366 days). Every
week has 7 days. Every month has 30 or 31 days except February which has 28 days in a
common calendar year and 29 days in a leap year.
Since 365 mod 7= 1, every year starts from the next day it’s from the day its preceding year
started. So if January 1, 2001, was Monday, January 1, 2002, will fall on a Tuesday because
2002 was not a leap year.
Though 11 months of a year have 30 or 31 days, some months begin exactly on the same day
as some other month.

Example:
April 2016 starts on Friday, so does July 2016. How?

April has 30 Days, May 31 days, and June has 30 days, which add up to 91.
91 modulo 7= 0, which returns a remainder of zero.
Hence, July starts the same day as April does.

The good news is that we have a bunch of months that start on the same day as some other
month of the year;
For common years:
 January and October
 February, March, and November
 April and July
 No month corresponds with August

For leap years:


 January, April, and July
 February and August
 March and November
 No month corresponds with October

Mat1-09-dates
200
G.A. El-Sheikh MATLAB: Introductory Course 201

Following these algorithms, Tomohiko Sakamoto developed an algorithm using the formula
above for the determination of a day of a week, which also took into consideration the
additional day in a leap year.

Let’s see how Tomohiko Sakamoto’s used the Doomsday Algorithm to determine the day of
the week.

January has 31 days, which if divided into a week of 7 days will give 7 ? 4 + 3 days, hence we
know that February 1 will be 3 days following the day that was January 1.
Similarly, 31 days of January + 28 days of February = 59 days, which is equal to 7 ? 8 +3, and
it makes sense when we say that March 1 will fall 3 days following the day that was January
1.
Thus, we get a subset of each month corresponding to January 1 {0,3,3,6,1,4,6,2,5,0,3,5},
where the first day of the month is represented by a number in the subset.
Now 365 days make a year, which is 7 ? 52 + 1.
This addition of an extra day every year is adjusted every 4 years as a leap year, that is,
February 29th.

So, every 4 years, the Gregorian calendar gains one extra day.
Which it doesn’t after 100 years and as the calendar repeats every 400 years, it again gains an
extra day in the 400th year.

Why do they have to make it so complicated?


To put things mathematically, we add an additional day as y/4 – y/100 + y/400.
Considering the rules above, which work for all calendars for a leap year, we must divide a
year by 4 to see if it is a leap year. But 100, though divisible by 4, can’t be a leap year, so you
subtract year/100. As mentioned, every 400 years it would be a leap year, hence add year/400.
With all the addition and subtraction, we accurately add that one day to the leap year.
Good, so we have mathematically adjusted the leap year. Not so difficult, right?
But the extra day comes in the month of February and not January.
We subtract a day from the first two months to make the algorithm work:

Mat1-09-dates
201
G.A. El-Sheikh MATLAB: Introductory Course 202

y -= m < 3

As we numbered the months from 1 to 12, for every month which has a value less than 3,
which in our case would be January and February, subtract 1 from its original value so
January becomes 0 and February become 1.
But doing this deletes a day from February and January even during non-leap years, which
leaves a blank day between February end and March 1. To avoid it, let’s subtract a day from
each month from March to December, making the list look like this:
{0,3,2,5,0,3,5,1,4,6,2,4}

The following codes will give Monday as 1 and Sunday as 7:

This finally gives us the following C++ code:


int dow(int y, int m, int d)
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
Copy

Here is a Python Code for the Algorithm


def day_of_week(year, month, day):
t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
year -= month < 3
return (year + int(year/4) - int(year/100) + int(year/400) + t[month-1] + day) % 7
Copy

Mat1-09-dates
202
G.A. El-Sheikh MATLAB: Introductory Course 203

9.4 Exercise-09
 Using MATLAB, design a program to calculate and display the calendar in a good format.

%**************************************
%*** calendar03d.m ***
%**************************************
%*** Calculates the Calendar for a given Year ***
%*** and month. ***
%*** It gives a 6-by-7 matrix containing the ***
%*** calendar for the specified year/month. ***
%*** The first column of the returned matrix ***
%*** corresponds to Sunday. ***
%*** It is a driver for; ***
%*** - calendar03f.m ***
%*** - calendar03h.m ***
%*** - calendar03h0.m ***
%**************************************
clc
clear
close all

disp(' 1- Available ')


disp(' 2- Keyboard one-month ')
disp(' 3- Keyboard whole-year ')
flag1 = input(' Select one of the above (default 1): ');
if isempty(flag1)==1, flag1=1;end;

if flag1==1
tmp1 = [2021 1];
Y1 = tmp1(1);
M1 = tmp1(2);
C1 = tmp1;
elseif flag1==2
tmp1 = input(' Enter Year and Month [Y M]: ');
Y1 = tmp1(1);
M1 = tmp1(2);
C1 = tmp1;
elseif flag1==3
Y1 = input(' Enter the Year: ');
M1 = 1;
C1 = [Y1 M1];
end

if flag1==1 || flag1==2
calendar03h0(C1)
calendar03h
X1 = calendar01f(Y1,M1);
[m1,n1] = size(X1);
for i1=1:m1;

Mat1-09-dates
203
G.A. El-Sheikh MATLAB: Introductory Course 204

disp(sprintf('\t%d\t',X1(i1,1:n1)))
disp([' -----------------------------------------'...
'-------------------------------------------'...
'------------------------------------------'])
end
elseif flag1==3
while M1<=12
calendar03h0(C1)
calendar03h
X1 = calendar01f(Y1,M1);
[m1,n1] = size(X1);
for i1=1:m1;
disp(sprintf('\t%d\t',X1(i1,1:n1)))
disp([' -----------------------------------------'...
'-------------------------------------------'...
'------------------------------------------'])
end
M1 = M1 + 1;
C1 = [Y1 M1];
end
end

function Y1 = calendar01f(c,m)
%**************************************
%*** Calculates the Calendar for a given Year ***
%*** and month. ***
%*** It gives a 6-by-7 matrix containing the ***
%*** calendar for the specified year/month. ***
%*** The first column of the returned matrix ***
%*** corresponds to Sunday. ***
%**************************************
if nargin == 0
c = clock;
c(3) = 1;
elseif nargin == 1
if (isnumeric(c) && ~isscalar(c)) || (ischar(c) && size(c,1) ~= 1)
error('MATLAB:calendar:NonScalarDate',...
'DATE must be scalar or a single string.');
end
c = datevec(c);
c(3) = 1;
else
if ~isscalar(c) || ~isscalar(m)
error('MATLAB:calendar:NonScalarArgs',...
'YEAR and MONTH must be scalars.');
end
if m < 1 || m > 12, ...
error('MATLAB:calendar:InvalidMonth',...
'MONTH must contain values between 1 and 12.'); end
c = [fix(c) fix(m) 1];

Mat1-09-dates
204
G.A. El-Sheikh MATLAB: Introductory Course 205

end

% Determine the week day for first day of the month.


k = rem(fix(datenum(c(1),c(2),c(3)))+5,7)+1;

% Determine number of days in the month.


dpm = [31 28 31 30 31 30 31 31 30 31 30 31];
d = dpm(c(2));
if (c(2) == 2) && ...
((rem(c(1),4) == 0 && ...
rem(c(1),100) ~= 0) || rem(c(1),400) == 0)
% Leap year February.
d = 29;
end

% Fix in the matrix.


x = zeros(7,6);
x(k:k+d-1) = 1:d;
x = x';

if nargout==0,
mths = ['Jan';'Feb';'Mar';'Apr';'May';'Jun';
'Jul';'Aug';'Sep';'Oct';'Nov';'Dec'];
mth = mths(c(:,2),:);
yr = sprintf('%.0f',c(1)+10000);
disp(sprintf(' %s %s',mth,yr(2:5)))
disp(' Su M Tu W Th F Sa')
disp(x)
else
Y1 = x;
end

%**************************************
%*** calendar03h.m ***
%**************************************
disp([' ==========================='...
'========================'...
'==================='])
disp([' Su M Tu '...
' W Th '...
' F Sa'])
disp([' ==========================='...
'========================'...
'==================='])

%**************************************
%*** calendar03h0.m ***
%**************************************
function calendar03h0(C1)

Mat1-09-dates
205
G.A. El-Sheikh MATLAB: Introductory Course 206

mths = ['Jan';'Feb';'Mar';'Apr';'May';'Jun';
'Jul';'Aug';'Sep';'Oct';'Nov';'Dec'];
mth = mths(C1(:,2),:);
yr = sprintf('%.0f',C1(1)+10000);

disp([' '...
'========================='...
' '])
disp(sprintf('\t\t\t\t\t | \t %s -- %s\t\t|',mth,yr(2:5)))

Output:
1- Available
2- Keyboard one-month
3- Keyboard whole-year
Select one of the above (default 1):
=========================
| Jan -- 2021 |
======================================================================
Su M Tu W Th F Sa
======================================================================
0 0 0 0 0 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 0 0 0 0 0 0
------------------------------------------------------------------------------------------------------------------------------

Mat1-09-dates
206
G.A. El-Sheikh MATLAB: Introductory Course 207

10- Solving Ordinary Differential Equations


10.1 Introduction
An ordinary differential equation (ODE) is a differential equation containing one or more
functions of one independent variable and the derivatives of those functions. The term
ordinary is used in contrast with the term partial differential equation which may be with
respect to more than one independent variable.

Differential Equations
A linear differential equation is a differential equation that is defined by a linear polynomial
in the unknown function and its derivatives, that is an equation of the form;
a 0 ( x ) y  a 1 ( x ) y  a 2 ( x ) y  a 3 ( x ) y    a n ( x ) y ( n )  b( x )  0

Where { a 0 ( x ), a 1 ( x ), a 2 ( x ), , a n ( x ), b( x ) } are arbitrary differentiable functions that do


not need to be linear, and { y , y, y,, y ( n ) } are the successive derivatives of the unknown
function y of the variable x.

Among ordinary differential equations, linear differential equations play a prominent role for
several reasons. Most elementary and special functions that are encountered in physics and
applied mathematics are solutions of linear differential equations. When physical phenomena
are modeled with non-linear equations, they are generally approximated by linear differential
equations for an easier solution. The few non-linear ODEs that can be solved explicitly are
generally solved by transforming the equation into an equivalent linear ODE.

Some ODEs can be solved explicitly in terms of known functions and integrals. When that is
not possible, the equation for computing the Taylor series of the solutions may be useful. For
applied problems, numerical methods for ordinary differential equations can supply an
approximation of the solution.

Ordinary differential equations (ODEs) arise in many contexts of mathematics and social and
natural sciences. Mathematical descriptions of change use differentials and derivatives.
Various differentials, derivatives, and functions become related via equations, such that a
differential equation is a result that describes dynamically changing phenomena, evolution,
and variation. Often, quantities are defined as the rate of change of other quantities (for
example, derivatives of displacement with respect to time), or gradients of quantities, which is
how they enter differential equations.

Specific mathematical fields include geometry and


analytical mechanics. Scientific fields include much of
physics and astronomy (celestial mechanics), meteorology
(weather modeling), chemistry (reaction rates), biology
(infectious diseases, genetic variation), ecology and
The trajectory of a projectile
population modeling (population competition), economics
launched from cannon follows a
(stock trends, interest rates and the market equilibrium curve determined by an ordinary
price changes). differential equation that is derived
from Newton's second law.
Many mathematicians have studied differential equations
and contributed to the field, including Newton, Leibniz, the Bernoulli family, Riccati,

Mat1-10-ode
207
G.A. El-Sheikh MATLAB: Introductory Course 208

Clairaut, d'Alembert, and Euler. A simple example is Newton's second law of motion; the
relationship between the displacement x and the time t of an object under the force F, is given
by the differential equation;
d 2 x(t )
m  F( x ( t ))
dt 2

which constrains the motion of a particle of constant mass m. In general, F is a function of the
position x(t) of the particle at time t. The unknown function x(t) appears on both sides of the
differential equation, and is indicated in the notation F(x(t)).

MATLAB is a powerful tool for solving ODEs via some of the builtin functions as follows;
 ODE45: Solve non-stiff differential equations, medium order method.
[TOUT,YOUT] = ODE45(ODEFUN,TSPAN,Y0)
With
‒ TSPAN = [T0 TFINAL] integrates the system of differential equations y' = f(t,y) from time T0
to TFINAL with initial conditions Y0.
‒ ODEFUN is a function handle.
‒ For a scalar T and a vector Y, ODEFUN(T,Y) must return a column vector corresponding
to f(t,y).
‒ Each row in the solution array YOUT corresponds to a time returned in the column vector
TOUT.
‒ To obtain solutions at specific times T0, T1,..., TFINAL (all increasing or all decreasing),
use TSPAN = [T0 T1 ... TFINAL].

[TOUT,YOUT] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS)

Solves as above with default integration properties replaced by values in OPTIONS, an


argument created with the ODESET function.

Commonly used options are scalar relative error tolerance 'RelTol' (1e-3 by default) and
vector of absolute error tolerances 'AbsTol' (all components 1e-6 by default).
If certain components of the solution must be non-negative, use ODESET to set the
'NonNegative' property to the indices of these components.

ODE45 can solve problems M(t,y)*y' = f(t,y) with mass matrix M that is nonsingular. Use
ODESET to set the 'Mass' property to a function handle MASS if MASS(T,Y) returns the
value of the mass matrix.
If the mass matrix is constant, the matrix can be used as the value of the 'Mass' option. If the
mass matrix does not depend on the state variable Y and the function MASS is to be called
with one input argument T, set 'MStateDependence' to 'none'. ODE15S and ODE23T can
solve problems with singular mass matrices.

[TOUT,YOUT,TE,YE,IE] = ODE45(ODEFUN,TSPAN,Y0,OPTIONS)

with the 'Events' property in OPTIONS set to a function handle EVENTS, solves as above
while also finding where functions of (T,Y), called event functions, are zero. For each
function you specify whether the integration is to terminate at a zero and whether the
direction of the zero crossing matters. These are the three column vectors returned by
EVENTS:
[VALUE,ISTERMINAL,DIRECTION] = EVENTS(T,Y).

Mat1-10-ode
208
G.A. El-Sheikh MATLAB: Introductory Course 209

For the I-th event function:


VALUE(I) is the value of the function, ISTERMINAL(I)=1 if the integration is to
terminate at a zero of this event function and 0 otherwise.

DIRECTION(I)=0 if all zeros are to be computed (the default), +1 if only zeros where the
event function is increasing, and -1 if only zeros where the event function is decreasing.
Output TE is a column vector of times at which events occur. Rows of YE are the
corresponding solutions, and indices in vector IE specify which event occurred.

SOL = ODE45(ODEFUN,[T0 TFINAL],Y0...)


returns a structure that can be used with DEVAL to evaluate the solution or its first derivative
at any point between T0 and TFINAL. The steps chosen by ODE45 are returned in a row
vector SOL.x.

For each I, the column SOL.y(:,I) contains the solution at SOL.x(I). If events were detected,
SOL.xe is a row vector of points at which events occurred. Columns of SOL.ye are the
corresponding solutions, and indices in vector SOL.ie specify which event occurred.
2.5
Example-10.1; 2
[t,y]=ode45(@vdp1,[0 20],[2 0]);
1.5
plot(t,y(:,1),'linewidth',3), grid on
1

This statement solves the system y' = 0.5

vdp1(t,y), using the default relative error 0

tolerance 1e-3 and the default absolute -0.5


tolerance of 1e-6 for each component, and -1
plots the first component of the solution.
-1.5

-2

-2.5
10.2 Solving one ODE 0 2 4 6 8 10 12 14 16 18 20

The solution of ODEs can be obtained via the following steps;


dy
1. Write the ODE in the form  ...
dt
dx Cx
For Example, the equation is  x 
dt 
2. Create a new M-file by selecting File>New>M-File
3. Write the ODE in M-file form using the following format:
function tempname = actualname(time, function, othervar)
tempname = …;

For the Example you might write:


function dxdt = fun1(t,x,C,tau)
dxdt = (C-x)/tau;

4. Save the M-file.


5. In the command window, use the following commands to solve the ODE and store it
in a vector:

Mat1-10-ode
209
G.A. El-Sheikh MATLAB: Introductory Course 210

[t, y] = ode45(@actualname, [time range],initial condition, [], other


variables);

For the Example you would write:

[t, x] = ode45(@fun1, [0 25], 0.5, [], 0.517, 3);

The empty brackets in the above statement are necessary and tell MATLAB to skip
the parameters t and x in the M-file conc.

6. Type the command plottools.


7. On the left hand side, click where it says “2D Axes”
8. On the right hand side, click the button “Add Data”
9. In the window that pops up select the appropriate vectors in the drop down menus
which hold the data you want to plot on the x and y axes. In our case we want to plot
“t” as the X Data Source and “x” as the Y Data Source. Then click OK.
10. You can add axis labels and a title by selecting Insert> and the appropriate label.

%***************************************
%*** dode01d.m ***
%***************************************
%*** First order ODE solution; ***
%*** dx/dt = (c-x)/tau ***
%*** It is driver for the function (dode01f.m) ***
%***************************************
clc
clear
close all
[t1, x1] = ode45(@dode01f, [0 25],0.5, [], 0.517,3);

plot(t1,x1,'b','linewidth',3), grid on
xlabel(' Time [sec]')
ylabel('Amplitude')
title (' Solution of ODE: dx/dt = (C-x)/ \tau')

function dxdt1 = dode01f(t,x,c,tau1);


%************************************ 0.52
Solution of ODE: dx/dt = (C-x)/ 

%*** dode01f.m ***


0.518
%************************************
%*** First order ODE solution; *** 0.516

%*** dx/dt = (c-x)/tau *** 0.514

%*** It is drived by (dode01d.m) *** 0.512


Amplitude

%************************************ 0.51
*** 0.508

0.506
dxdt1 = (c-x)/tau1;
0.504

The solution has the following time response; 0.502

0.5
0 5 10 15 20 25
Time [sec]

Mat1-10-ode
210
G.A. El-Sheikh MATLAB: Introductory Course 211

10.3 Solving two ODE’s Simultaneously


dy
1. Write both ODE’s in the form  ...
dt
For this example, the equations are
dV 1
 ( w1  w2  w)
dt 
dx w1 w
 ( x1  x)  2 ( x 2  x)
dt V V
2. On paper, set up a vector that will contain all of the functions for which you want to
solve. This vector will have a corresponding first derivative vector that holds the
derivative functions from step 1.
 dy1 dy 2 dy 3 
y1 y2 y3 ...  dt ...
 dt dt 
For our example we will use the vectors:
 dV dx 
V x  dt dt 
Let
y1  V
y2  X
Then,
  (w  w  w) / 
y 1  V 1 2
  w ( x  y )  w ( x  y ) / y / 
y 2  X 1 1 2 2 2 2 1

3. Create a new M-file by selecting File>New>M-File


4. Write the ODE’s in M-file form using the following format:
function tempname = actualname(time, vectorfunction, othervar)
tempname = [function1; function2; function3; …];

For our example you might write:


function dydt = Volconc(t,y,w1,w2,w,x1,x2,rho)
dydt = [(w1+w2-w)/rho; (w1*(x1-y(2))+w2*(x2-y(2)))/(y(1)*rho)];

Notice that the vector which will hold our solutions for both V and x is called y. We
must therefore refer to V as y(1) and x as y(2) in the function statement.
5. Save the M-file.
6. In the command window, use the following commands to solve the ODE and store it
in a vector:

[t, y] = ode45(@actualname, [time range],[initial condition1; initial


condition2;…], [], other variables);

For our example you would write:


[t,y]=ode45(@Volconc,[0 25],[2;0.5],[],400,200,700,0.4,0.75,900);

The empty brackets in the above statement are necessary and tell MATLAB to skip the
parameters t and y in the M-file Volconc.

Mat1-10-ode
211
G.A. El-Sheikh MATLAB: Introductory Course 212

7. Type the command plottools.


8. On the left hand side, click where it says “2D Axes”
9. On the right hand side, click the button “Add Data”
10. In the window that pops up select the appropriate vectors in the drop down menus
which hold the data you want to plot on the x and y axes. In our case we want to plot
“t” as the X Data Source and “y” as the Y Data Source. Then click OK.
11. If you don’t want all the functions plotted on the same graph you can select the data
you don’t want on the graph, right click and select Cut. Then you can click “2D
Axes” again to get a new set of axes to plot the other functions.
12. You can add axis labels and a title by selecting Insert> and the appropriate label.

%***************************************
%*** dode02d.m ***
%***************************************
%*** First order ODE solution; ***
%*** dv/dt = (w1+w2-w)/roh1 ***
%*** dx/dt = {w1(x1-x)+w2(x2-x)}/v/roh1 ***
%*** It is driver for the function (dode02f.m) ***
%***************************************
clc
clear
close all

% [t1, y1] = ode45(@dode02f, [0 10], [2;0.5], [],...


% 400,200,700,0.4,0.75,900);
[t1, y1] = ode45(@dode02f, [0 10], [3;0.7], [],...
500,150,600,0.5,0.8,800);
figure
plot(t1,y1(:,1),'b','linewidth',3), grid on
xlabel(' Time [sec]')
ylabel('Amplitude')
title(' Solution of ODE: dv/dt = (w_1+w_2-w) / \rho')

figure
plot(t1,y1(:,2),'r--','linewidth',3), grid on
xlabel(' Time [sec]')
ylabel('Amplitude')
title(' Solution of ODE: dx/dt = {w_1(x_1-x)+w_2(x_2-x)}/ v / \rho')

function dxdt1 = dode02f(t,y,w1,w2,w,x1,x2,roh1);


%***************************************
%*** dode02f.m ***
%***************************************
%*** Two first order ODE solution; ***
%*** dv/dt = (w1+w2-w)/roh1 ***
%*** dx/dt = {w1(x1-x)+w2(x2-x)}/v/roh1 ***
%*** It is drived by (dode02d.m) ***
%***************************************

Mat1-10-ode
212
G.A. El-Sheikh MATLAB: Introductory Course 213

dxdt1 = [(w1+w2-w)/roh1;
(w1*(x1-y(2))+ w2*(x2-y(2)))/y(1)/roh1];

The solution has the following time response;

Solution of ODE: dv/dt = (w1+w2-w) / 


3.8

3.7

3.6

3.5
Amplitude

3.4

3.3

3.2

3.1

3
0 1 2 3 4 5 6 7 8 9 10
Time [sec]

Solution of ODE: dx/dt = w1(x 1-x)+w2(x 2-x)/ v / 


0.7

0.68

0.66

0.64
Amplitude

0.62

0.6

0.58

0 1 2 3 4 5 6 7 8 9 10
Time [sec]

Mat1-10-ode
213
G.A. El-Sheikh MATLAB: Introductory Course 214

10.4 Newton-Raphson Method MATLAB Program


Newton-Raphson method, named after Isaac Newton and Joseph Raphson, is a popular
iterative method to find the root of a polynomial equation. It is also known as Newton’s
method, and is considered as limiting case of secant method.

Based on the first few terms of Taylor’s series, Newton-Raphson method is more used when
the first derivation of the given function/equation is a large value. It is often used to improve
the value of the root obtained using other rooting finding methods in Numerical Methods. We
have already discussed C-program and algorithm/flowchart for Newton’s method in earlier
tutorials. Here, we are going to go through a sample program code for Newton Raphson
method in MATLAB, along with a numerical example and theoretical background.

Derivation of Newton-Raphson Method:


The theoretical and mathematical background behind Newton-Raphson method and its
MATLAB program (or program in any programming language) is approximation of the given
function by tangent line with the help of derivative, after choosing a guess value of root which
is reasonably close to the actual root.

The x- intercept of the tangent is


calculated by using elementary
algebra, and this calculated x-
intercept is typically better
approximation to the root of the
function. This procedure is
repeated till the root of desired
accuracy is found.

Lets now go through a short


mathematical background of
Newton’s method. For this,
consider a real value function
f(x) as shown in the figure.

Consider x1 to be the initial guess root of the function f(x) which is essentially a differential
function. Now, to derive better approximation, a tangent line is drawn as shown in the figure.
The equation of this tangent line is given by:
y = f’(x1) (x- x1) + f(x1)
where, f’(x) is the derivative of function f(x).
As shown in the figure, f(x2) = 0 i.e. at x = x2, y=0
Therefore, 0 = f’(x1) (x2– x1) + f(x1)
Solving, x2 = x1 – f(x1) / f’(x1)

Repeating the above process for xn and xn+1 terms of the iteration process, we get the general
iteration formula for Newton-Raphson Method as:
xn+1 = xn – f(xn)/f’(xn)

This formula is used in the program code for Newton Raphson method in MATLAB to find
new guess roots.

Mat1-10-ode
214
G.A. El-Sheikh MATLAB: Introductory Course 215

Steps to find root using Newton’s Method:


1. Check if the given function is differentiable or not. If the function is not differentiable,
Newton’s method cannot be applied.
2. Find the first derivative f’(x) of the given function f(x).
3. Take an initial guess root of the function, say x1.
4. Use Newton’s iteration formula to get new better approximate of the root, say x2
x2 = x1 – f(x1)/f’(x1)
5. Repeat the process for x3, x4… till the actual root of the function is obtained, fulfilling
the tolerance of error.

10.4.1 Newton Raphson Method in MATLAB


MATLAB Program for Newton-Raphson Method;

1 % Program Code of Newton-Raphson Method in MATLAB


2
3 a=input('Enter the function in the form of variable x:','s');
4 x(1)=input('Enter Initial Guess:');
5 error=input('Enter allowed Error:');
6 f=inline(a)
7 dif=diff(sym(a));
8 d=inline(dif);
9 for i=1:100
10 x(i+1)=x(i)-((f(x(i))/d(x(i))));
11 err(i)=abs((x(i+1)-x(i))/x(i));
12 if err(i)<error
13 break
14 end
15 end
16 root=x(i)

In this code for Newton’s method in Matlab, any polynomial function can be given as input.
Initially in the program, the input function has been defined and is assigned to a variable ‘a’.
After getting the initial guess value of the root and allowed error, the program, following
basic MATLAB syntax, finds out root undergoing iteration procedure as explained in the
theory above.

Here’s a sample
output of this code:

Mat1-10-ode
215
G.A. El-Sheikh MATLAB: Introductory Course 216

10.4.2 Newton-Raphson Method Example


Now, let us analyze the above program of Newton-Raphson method in Matlab, taking the
same function used in the above program and solving it numerically. The function is to be
corrected to 9 decimal places.
Solution:
Given function: x3−x−1 = 0, is differentiable.
The first derivative of f(x) is f’(x) = 3x2 – 1
Lets determine the guess value;
f(1) = 1 -1 -1 = -1 and f(2) = 8 – 2 -1 = 5

Therefore, the root lies in the interval [1, 2]. So, assume x 1= 1.5 as the initial guess root of the
function f(x) = x3−x−1.
Now,
f(1.5) = 1.53 – 1.5 – 1 = 0.875
f’(1.5) = 3 * 1.52– 1 = 5.750
Using Newton’s iteration formula:
x2 = x1 – f(x1)/f’(x1) = 1.5 – 0.875/5.750 = 1.34782600
The iteration for x3, x4, …. is done similarly.

The table below shows the whole iteration procedure for the given function in the program
code for Newton Raphson in MATLAB and this numerical example.

Therefore, x = 1.324717957 is the desired root of the given function, corrected to 9 decimal
places. The MATLAB program gives the result x = 1.3252 only, but this value can be
improved by improving the value of allowable error entered.

Mat1-10-ode
216
G.A. El-Sheikh MATLAB: Introductory Course 217

Program:
%************************************
%*** newtonraphson01.m ***
%************************************
clc
clear
close all

% Program Code of Newton-Raphson Method in MATLAB

a = input('Enter the function in the form of variable x:','s');


x(1) = input('Enter Initial Guess:');
error = input('Enter allowed Error:');
f = inline(a)
dif = diff(sym(a));
d = inline(dif);
for i=1:100
x(i+1) = x(i)-((f(x(i))/d(x(i))));
err(i) = abs((x(i+1)-x(i))/x(i));
if err(i)<error
break
end
end
root = x(i)

Enter the function in the form of variable x:x^3-2*x^2+x+16


Enter Initial Guess:.1
Enter allowed Error:.001
f=
Inline function:
f(x) = x^3-2*x^2+x+16
root =
-1.9016
>>

Enter the function in the form of variable x:x^3-x-1


Enter Initial Guess:1.5
Enter allowed Error:0.001
f=
Inline function:
f(x) = x^3-x-1
root =
1.3252
>>

Mat1-10-ode
217
G.A. El-Sheikh MATLAB: Introductory Course 218

10.4.3 Example-10.5
Using Newton-Raphson Method with initial guess (x0 = 0.05), design a program to solve the
equation:
f(x) = x.^3 - 0.165*x.^2 + 3.993*10.^-4
up to 3 iterations and plot that function.

Using (newtonraphson01.m) the results are;


Enter the function in the form of variable x: x^3 - 0.165*x^2 + 3.993e-4
Enter Initial Guess:0.05
Enter allowed Error:0.001
f=
Inline function:
f(x) = x^3 - 0.165*x^2 + 3.993e-4
root =
0.0624
>>
1000

%************************************
%*** newtonraphson02.m *** 500

%************************************
clc 0
clear
close all
-500

x = 0.05;
x_old = 100; -1000
x_true = 0.0623776;
iter = 0;
-1500
while abs(x_old-x) > 10^-3 && x ~= 0 0 500 1000 1500 2000 2500

x_old = x;
x = x - (x^3 - 0.165*x^2 + 3.993*10^-4)/(3*x^2 - 0.33*x);
iter = iter + 1;
fprintf('Iteration %d: x=%.20f, err=%.20f\n', iter, x, x_true-x);
end

x = -10:0.01:10;
f = x.^3 - 0.165*x.^2 + 3.993e-4;
figure;
plot(f,'r','linewidth',3), grid on

Results;
Iteration 1: x=0.06242222222222221200, err=-0.00004462222222221396
Iteration 2: x=0.06237757654346584600, err=0.00000002345653415253
>>

Mat1-10-ode
218
G.A. El-Sheikh MATLAB: Introductory Course 219

10.4.4 Example-10.6
Solve the system of non-linear equations;
x^2 + y^2 = 2z
x^2 + z^2 =1/3
x^2 + y^2 + z^2 = 1

Using Newton’s method having tolerance = 10^(−5) and maximum iterations up-to 25.

%************************************
%*** newtonraphson03.m ***
%************************************
clc
clear
close all

fn = @(v) [v(1)^2+v(2)^2-2*v(3) ;
v(1)^2+v(3)^2-(1/3);
v(1)^2+v(2)^2+v(3)^2-1];
jacob_fn = @(v) [2*v(1) 2*v(2) -2 ;
2*v(1) 0 2*v(3) ;
2*v(1) 2*v(2) 2*v(3)];
err1 = 10^-5 ;
v = [1 ;1 ;0.1] ;
n1 = 24 ;
[point,n1,error_out] = nraphson03f(v,fn,jacob_fn,n1,err1)
nraphson03p(v,fn,jacob_fn,n1,err1);

function [v1 , no_itr, norm1] = nraphson03f(v,fn,jacob_fn,no_itr,error)


% nargin = no. of input arguments
if nargin <5 , no_itr = 20 ; end
if nargin <4 , error = 10^-5;no_itr = 20 ; end
if nargin <3 ,no_itr = 20;error = 10^-5; v = [1;1;1]; end

v1 = v;
fnv1 = feval(fn,v1);
i = 0;
while true
jacob_fnv1 = feval(jacob_fn,v1);
H = jacob_fnv1\fnv1;
v1 = v1 - H;
fnv1 = feval(fn,v1);
i=i+1;
norm1 = norm(fnv1);
if i > no_itr && norm1 < error, break , end
%if norm(fnv1) < error , break , end
end
end

Mat1-10-ode
219
G.A. El-Sheikh MATLAB: Introductory Course 220

function [v1 , no_itr, norm1] = nraphson03p(v,fn,jacob_fn,no_itr,error)


v1 = v;
fnv1 = feval(fn,v1);
i = 0;
fprintf(' Iteration| x | y | z | Error | \n')
while true
norm1 = norm(fnv1);
fprintf('%10d |%10.4f| %10.4f | %10.4f| %10.4d |\n',i,v1(1),v1(2),v1(3),norm1)
jacob_fnv1 = feval(jacob_fn,v1);
H = jacob_fnv1\fnv1;
v1 = v1 - H;
fnv1 = feval(fn,v1);
i=i+1;
norm1 = norm(fnv1);
if i > no_itr && norm1 < error, break , end
%if norm(fnv1) < error , break , end
end
end

point =
0.4022
0.8165
0.4142
n1 =
24
error_out =
5.5511e-017
Iteration| x | y | z | Error |
0 | 1.0000| 1.0000 | 0.1000| 2.1721e+000 |
1 | 0.6258| 0.8333 | 0.4591| 4.3429e-001 |
2 | 0.4432| 0.8167 | 0.4149| 6.0297e-002 |
3 | 0.4041| 0.8165 | 0.4142| 2.6538e-003 |
4 | 0.4022| 0.8165 | 0.4142| 6.2251e-006 |
5 | 0.4022| 0.8165 | 0.4142| 3.4577e-011 |
6 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
7 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
8 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
9 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
10 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
11 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
12 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
13 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
14 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
15 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
16 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
17 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
18 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
19 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
20 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
21 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
22 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
23 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
24 | 0.4022| 0.8165 | 0.4142| 5.5511e-017 |
>>

Mat1-10-ode
220
G.A. El-Sheikh MATLAB: Introductory Course 221

10.4.5 Newton-Raphson Method Codes for MATLAB


Newton-Raphson method is implemented here to determine the roots of a function.
This algorithm is coded in MATLAB m-file. There are three files: func.m, dfunc.m
and newtonraphson.m. The func.m defines the function, dfunc.m defines the
derivative of the function and newtonraphson.m applies the Newton-Raphson
method to determine the roots of a function.

Example-10.7:
Evaluating the root of,
f(x)=sin(x)
Solution:
%************************************
%*** newtonraphson04.m ***
%************************************
clc
clear
close all

% applies Newton Raphson algorithm to determine the roots of a function


close all;
clear all;
x = input('Starting guess = ');
tolerance = 1e-8;
iterations = 0;
while (iterations<100) && (abs(nraphson04f(x))>tolerance)
x = x-(nraphson04f(x)/nraphson04d(x));
iterations = iterations + 1;
end
if iterations==100
disp('No root found')
else
disp(x)
end

% defines the function as its roots to be determined


function [sol1] = nraphson04f(x)
sol1=sin(x); Output:

% defines the derivative of the function Starting guess = 1


function [dsol1]=nraphson04d(x) 2.9236e-13
dsol1=cos(x);
Starting guess = 0.1
1.2495e-11

Starting guess = 0.01


1.2335e-20

Mat1-10-ode
221
G.A. El-Sheikh MATLAB: Introductory Course 222

Example-10.8:
Evaluating the root of,
F1(x) = sin(x)
F2(x) = x-2*sin(xˆ2)
F3(x) = x^2 - 5
Solution:
%************************************
%*** newtonraphson08.m ***
%************************************
clc
clear
close all

f1 = @(x) sin(x);
r1 = nraphson08f(f1, 2, 5)

f2 = @(x) (x-2*sin(x^2));
r2 = nraphson08f(f2, 1, 10)

f3 = @(x) (x^2 - 5);


r3 = nraphson08f(f3, 0.1, 10)

function r1 = nraphson08f(f1,r0,n1)
syms x1;
z1 = f1(x1);
diffZ = diff(z1); % Edit - Include derivative
y1 = r0; % Initial root

for idx = 1 : n1
numZ = subs(z1,x1,y1); % Numerator - Substitute f(x) for f(y)
denZ = subs(diffZ,x1,y1); % Denominator - Substitute for f'(x) for f'(y)
% Update - Cast to double to get the numerical value
y1 = y1 - double(numZ)/double(denZ);
end
r1 = y1; % Send to output
end

Output
r1 =
3.1416
r2 =
0.5055
r3 =
2.2361
>>

Mat1-10-ode
222
G.A. El-Sheikh MATLAB: Introductory Course 223

Example-10.9:
Evaluating the root of,
F1(x) = sin(x)
F2(x) = x-2*sin(xˆ2)
F3(x) = x^2 - 5
Solution:
%************************************
%*** newtonraphson09.m ***
%************************************
clc
clear
close all

f1 = @(x) sin(x);
r1 = nraphson09f(f1, 2, 5)

f2 = @(x) (x-2*sin(x^2));
r2 = nraphson09f(f2, 1, 7)

f3 = @(x) (x^2 - 5);


r3 = nraphson09f(f3, 0.1, 7)

function [y2] = nraphson09f(f1,r0,n1)


syms x1;
z1 = f1(x1);
diffZ = diff(z1); % Edit - Include derivative
y1 = zeros(1,n1+1); % Pre-allocate output array
y1(1) = r0; % First entry is the initial root

for idx = 1 : n1
% Remember to use PREVIOUS guess for next guess
numZ = subs(z1,x1,y1(idx));
denZ = subs(diffZ,x1,y1(idx));
% Place next guess in right spot
y1(idx+1) = y1(idx) - double(numZ)/double(denZ);
end
y2 = y1; % Send to output

Output:
r1 =
2.0000 4.1850 2.4679 3.2662 3.1409 3.1416
r2 =
1.0000 0.4119 0.5308 0.5065 0.5055 0.5055 0.5055 0.5055
r3 =
0.1000 25.0500 12.6248 6.5104 3.6392 2.5066 2.2507 2.2361
>>

Mat1-10-ode
223
G.A. El-Sheikh MATLAB: Introductory Course 224

Example-10.10:
Evaluating the root of;
F(x) = x-2*sin(xˆ2)
Solution: Output:

Starting guess = 0.1


% defines the function as its roots to be determined
-1.0489e-10
function [sol1] = nraphson05f(x)
sol1 = x-(2*sin(x.^2));
Starting guess = 0.3
-2.4565e-10
% defines the derivative of the function
function [dsol1] = nraphson05d(x) Starting guess = 1
dsol1 = 1-(4*x*cos(x)); 0.5055

Example-10.11:
Evaluating the root of;
F(x) = x^2 - 5 Output:
Solution:
% defines the function as its roots to be determined Starting guess = 2
function [sol1] = nraphson06f(x) 2.2361
sol1 = x^2 - 5;
Starting guess = 3
% defines the derivative of the function 2.2361
function [dsol1] = nraphson06d(x)
dsol1 = (2*x); Starting guess = 0.01
2.2361

Mat1-10-ode
224
G.A. El-Sheikh MATLAB: Introductory Course 225

11- Errors and Warnings


In many cases, it's desirable to take specific actions when different kinds of errors occur. For
example, you may want to prompt the user for more input, display extended error or warning
information, or repeat a calculation using default values. MATLAB's error handling
capabilities let your application check for particular error conditions and execute appropriate
code depending on the situation.

11.1 Error Handling with eval and lasterr


The basic tools for error-handling in MATLAB are:
 The eval function, which lets you execute a function and specify a second function to
execute if an error occurs in the first.
 The lasterr function, which returns a string containing the last error generated by
MATLAB.
The eval function provides error-handling capabilities using the two- argument form
eval ('trystring','catchstring')
If the operation specified by trystring executes properly, eval simply returns. If
trystring generates an error, the function evaluates catchstring. Use catchstring to specify
a function that determines the error generated by trystring and takes appropriate action.
The trystring/catchstring form of eval is especially useful in conjunction with the
lasterr function. lasterr returns a string containing the last error message generated by
MATLAB. Use lasterr inside the catchstring function to "catch" the error generated
by trystring. For example, this function uses lasterr to check for a specific error
message that can occur during matrix multiplication. The error message indicates that matrix
multiplication is impossible because the operands have different inner dimensions. If the
message occurs, the code truncates one of the matrices to perform the multiplication.
function C = catchfcn(A,B)
l = lasterr;
j = findstr(l,'Inner matrix dimensions')
if (~isempty(j))
[m,n] = size(A)
[p,q] = size(B)
if (n>p)
A(:,p+1:n) = []
elseif (n<p)
B(n+1:p,:) = []
end
C = A*B;
else
C = 0;
end
This example uses the two-argument form of eval with the catchfcn function shown
above.
clear
A = [1 2 3; 6 7 2; 0 1 5];
B = [9 5 6; 0 4 9];
eval('A*B','catchfcn(A,B)')
A = 1:7;
B = randn(9,9);
eval('A*B','catchfcn(A,B)')

Mat1-11-errors
225
G.A. El-Sheikh MATLAB: Introductory Course 226

11.2 Displaying Error and Warning Messages


Use the error and fprintf functions to display error information on the screen. The error
function has the syntax
error('error string')
If you call the error function from inside an M-file, error displays the text in the quoted
string and causes the M-file to stop executing. For example, suppose the following appears
inside the M-file myfile.m.
if n < 1
error('n must be 1 or greater.')
end
For n equal to 0, the following text appears on the screen and the M-file stops.
??? Error using ==> myfile
n must be 1 or greater.

In MATLAB, warnings are similar to error messages, except program execution does not
stop. Use the warning function to display warning messages.
warning('warning string')
The function lastwarn displays the last warning message issued by MATLAB.

Mat1-11-errors
226
G.A. El-Sheikh MATLAB: Introductory Course 227

12- Creating a GUI in Matlab


One of the major comments that we hear about Matlab is "I don't know how I can use it in my
classroom. It is too hard for my students to use." This may be a correct comment - we don't
necessarily want the students to
construct a model from scratch in
Matlab, but would want them to use a
previously prepared model. We can do
this using Input and disp statements in
a M-file which is run from the Matlab
window. A much better way is to use a
Graphical User Interface (GUI) where
the student just "fills in the blanks" and
all of the Matlab commands are
completely hidden from the student.

Creating GUI's in Matlab is significantly easy, the guide program allows one to easily place
controls onto a model and set their properties. In the following exercise, we will
construct a GUI which will calculate the Black-Body temperature of a planet near the sun. As
outlined in the Energy Balance Model handout the black-body temperature is defined as,

T = [S*SX(1- )/4 / ] 1/4-T0

Where the symbols are defined as:


T The Temperature of the Earth in Centigrade
S Solar Constant (1370 W/m2) at surface of earth
SX Solar Multiplier (Fraction of Earth's Solar Flux)
Albedo - Fraction of incident solar radiation reflected
(about 0.32)
Stefan's Constant (5.6696E-8 W/m2K4)
T0 Conversion from Kelvin to Centigrade (273.15)

Now, we are going to develop a Matlab GUI which allows a person to find the black-body
temperature using this equation,

1. Type "guide" in the Matlab Control Window to start the GUI editor. You should see a
Figure Window which has dotted lines in it, and the "Guide Control Panel" window
(which I will abbreviate GCP window.
2. Click on the "Text" box at the bottom of the GCP window, then click at some point on
the Figure window, and it will create a box - this is the box that we will want to
contain the text 'Solar Multiplier'
3. Double click on the box we just created and the "Guide Property Editor" window will
pop up. This allows us to set the properites of the text box. In the white region of the
window erase the word BackgroundColor and type in String and press enter. In the
next region, it will display two single quotes (''). Type in the words Solar
Multiplier between the quotes and press enter
4. The string will now be displayed in the text box on the figure. You may need to resize
it my dragging on one of the corners of the text box.

Mat1-12-gui
227
G.A. El-Sheikh MATLAB: Introductory Course 228

5. Now we will want to make the box where the user will type a value for the solar
multiplier. To do this, click on the "Edit" box in the GCP to create an edit-text box
(where the user can type in the value for the solar multiplier). Place it near the text
box that we just created. This should be white with a black border
6. Double click the edit-text box. We will want to set is String to '1' We also need to
set a "Tag" for this box (so we can read the string that is in the box in our calculation
program). I used the tag 'SX' (all caps) for this box
7. Repeat the operations above to create a text box with the string 'Albedo' and a
editable-text box which contains the string '0.32' and has a tag of 'Albedo'
8. In the GCP, select Pushbutton, and place it at some location on the screen.
9. Double-click on the pushbutton and set its string to 'Calculate'
10. When we click this pushbutton, we want Matlab to run a script called ebm0calc. To
do this we set the CallBack property for this button to 'ebm0calc' The callback
property is a Matlab command (or series of commands separated by semicolons)
which are executed when the button is pressed.
11. Finally, we need a place to display the final temperature. Make two text boxes and set
their BackgroundColor to Cyan. In one box, put the string 'Blackbody Temperature'
and for the other box, give it a Tag property of TFinal. This is where we will write
the final temperature.
12. At this point, our GUI is complete and should look somewhat like the figure below.
13. Under the Options menu, choose, Activate Figure and save it as ebm0gui.m By
activating the figure, we leave the GUI editor and enable Matlab to process the buttons
we have defined. The file ebm0gui.m contains the Matlab commands to generate this
screen.

Now we are ready to create the file ebm0calc.m which will perform the calculations and
display the results on the screen. The file below will do this:
% Energy Balance Model for Eqn 1 in
% http://physics.gac.edu/~huber/envision/instruct/ebm1doc.htm
% Based on Equation 3.8
% from 'A Climate Modeling Primer', 1st Edition, 1987
% A. Henderson-Sellers and K. McGuffie
%
% Requires EBM0GUI - GUI Front end to set up values

S = 1370; % Solar Constant (W/m^2)


Sigma = 5.6696E-8; % Steffan's Constant (in W/m^2K^4)
T0 = 273.15; % Kelvin -> Centigrade Conversion

% Get the Albedo Value (from the object with a tag "Albedo"
% the property we want is the "String"
% Must do a str2num conversion to convert from the string
% to a number
HH = findobj(gcf,'Tag','Albedo');
albedo = str2num(get(HH,'String'));
HH = findobj(gcf,'Tag','SX');
SX = str2num(get(HH,'String'));

TFinal = (S*SX*(1-albedo)/4/Sigma)^.25;
Units = ' C'; % Degrees Centigrade
TFinal = TFinal - T0; %Convert from Kelvin to Centigrade

% Get the Handle for the TFinal Tag

Mat1-12-gui
228
G.A. El-Sheikh MATLAB: Introductory Course 229

HH = findobj(gcf,'Tag','TFinal');
% Set the string for the object TFinal
set(HH,'String',[num2str(TFinal) Units])

There are a couple of things that we should note:


1. We obtain the values for albedo and SX by first finding their handles using the
command
2. HH = findobj('Tag','Albedo');
3. Then we read the string using the get(HH,'String') and use str2num to get the
values.
4. Similarly, to set the display for TFinal, we first find its handle using HH =
findobj(gcf,'Tag','TFinal');
5. Then we set the value using set(HH,'String',[num2str(TFinal) Units])

Mat1-12-gui
229
G.A. El-Sheikh MATLAB: Introductory Course 230

Essential parameters to create a GUI with Matlab


Creating a suitable interface;
First of all to create a Matlab interface, is to use the { >>guide } command which opens a
certain interface with GUI toolbar,

Each object dragged from the toolbar to the blanc new sheet is called object, and its
property is got by double clicking on it to get the property inspector, each parameter is
adjusted by its default value and can be changed by the user if necessary.

The mostly changed


properties are:
1- The background
color.
2- String (which is
the name
displayed on the
object)
3- Tag, (the name of
the object in the
program

Mat1-12-gui
230
G.A. El-Sheikh MATLAB: Introductory Course 231

An example for the GUI, is that which accepts 3 parameters and draw certain functions in 2
separate axes, when the specified button is pressed.

By saving the GUI, two files are generated, (.fig) and (.m) , the m file is automatic generated
code contains some functions. Each object in the GUI has two functions: 1-opening function
& 2-call back function.

The opening function is usually not edited, but the call back function is edited when there is
a certain action we want it to happen when we change an object state on the GUI, like clicking
a button or choose item from list …and so on.

The next table summarizes the necessary codes which must be added to the m file;
Object Getting data Putting data
Edit box no1=str2num(get(handles.edit1, 'String')); set(handles.edit1, 'String', num2str(no1);
Tag=edit1 We used str2num and num2str if we want to get put the string koko in edit1
(or static text) or put numbers in the GUI, and ignored if string set(handles.edit1, 'String', 'koko'));
is wanted.
checkbox c1=get(handles.checkbox1, 'Value'); set(handles.checkbox1, 'Value', 1);
Tag= value is one if check box is checked set(handles.checkbox1, 'Value', 0);
checkbox1
radiobutton c1=get(handles. radiobutton1, 'Value'); set(handles. radiobutton1, 'Value', 1);
Tag= value is one if radiobutton is choosed set(handles. radiobutton1, 'Value', 0);
radiobutton1
List box and choice1=get(handles. listbox1, 'Value'); set(handles. listbox1, 'Value', 3);
popup menu value is 1,2,3,4,… and so on according to the to put the choice on the 3rd choice
number of items in the list, then if condition or
switch case is used to decide the function of each
choice.
Items in the list is written in the object property

Mat1-12-gui
231
G.A. El-Sheikh MATLAB: Introductory Course 232

inspector, in the string property


Slider s1=get(handles. slider1, 'Value'); set(handles. slider1, 'Value', s1);
Tag=slider1 s1 is a variable contains the required value
Toggle button c1=get(handles.tb1, 'Value'); set(handles. tb1, 'Value', 1);
Tag=tb1 value is one if Toggle button is pressed set(handles. tb1, 'Value', 0);

Axes axes(handles.axes1) % Select the proper axes


Tag=axes1 plot(x,y)

From the previous table we found that only two properties are used (string in case of editbox
or static text or value for the rest of objects)

Other properties are commonly used like:


*Visible, to control the visibility of the object
Ex:
set(handles. tb1, 'Visible', 'off');
set(handles. tb1, 'Visible', 'on');

*Enable
set(handles. tb1, 'Enable', 'off');
set(handles. tb1, 'Enable', 'on');

which enable/disable the object

Example:
In the previously shown GUI the code added to the m file under the plot button call back
function as follows:

function plot_button_Callback(hObject, eventdata, handles)


% hObject handle to plot_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get user input from GUI


f1 = str2double(get(handles.f1_input,'String'));
f2 = str2double(get(handles.f2_input,'String'));
t = eval(get(handles.t_input,'String'));

% Calculate data
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
y = fft(x,512);
m = y.*conj(y)/512;
f = 1000*(0:256)/512;;

% Create frequency plot


axes(handles.frequency_axes) % Select the proper axes
plot(f,m(1:257))
set(handles.frequency_axes,'XMinorTick','on')
grid on

% Create time plot


axes(handles.time_axes) % Select the proper axes
plot(t,x)
set(handles.time_axes,'XMinorTick','on')
grid on

Mat1-12-gui
232
G.A. El-Sheikh MATLAB: Introductory Course 232

13- Revision: MATLAB Computer Sessions


 Entering matrices:
>> A=[12 13 14; 10 45 67; 56 78 99] Display the matrix on monitor
>> A=[12 13 14; 10 45 67; 56 78 99]; Suppress displaying the matrix on monitor
>> A=[12 13 14 Entering the matrix (especially the big
10 45 67 matrices) rows in different lines, each ro in a
line
56 78 99];
>> mat1 The m-file (mat1.m) contains any of the
above format. It is created in any text editor.

>> B=[1 3 4; 100 450 670]; Enter another matrix


>> C1=[A; B]; Construct a new matrix C1 from the matrix
A and B attached to the end of A.
>> C2=[A; B’]; Construct a new matrix C2 from the matrix
A and B attached to the right of A.
>> C3=C2(1:2,:) Extract the first two rows from the matrix
C2 and assigned them to the new variable C3
>> C4=C1(:,1:2) Extract the first two columns from the
matrix C1 and assigned them to the new
variable C4

 Matrix operations:
>> A’ Display the matrix transpose on monitor
>> inv(A) Display the matrix inverse on monitor
>> C=B+A Matrix addition element by element, i.e. the two matrices should
have the same dimensions
>> C=B-A Matrix subtraction element by element, i.e. the two matrices should
have the same dimensions
>> C=B’*A Matrix multiplication, where the dimensions of the two matrices
should be matched.

 Matrix divisions and equation solution:


>> x=A \ B Gives the solution to the equation:
A*x = B
>> x=B / A Gives the solution to the equation:
x*A = B
If A is non-singular square matrix, then A\B and B/A correspond
to left and right multiplication of B by the inverse of A i.e.
inv(A)*B and B*inv(A).
>> A^n Raises the matrix A to n-th power i.e. A*A*..............*A (n-
times)
>> A .^ n Raises the matrix A-elements to n-th power, individually.

 Array operations:

Mat1-13-sessions
232
G.A. El-Sheikh MATLAB: Introductory Course 233

>> x.^n Raises the array x-elements to n-th power, individually.

 Data generations:
>> magic(n) Generates an n-by-n matrix from integers from 1 to
n^2 with equal row and column sums.
>> eye(n) Generates an n-by-n identity matrix i.e.
matrix with zero elements except the diagonal
elements are all ones.
>> ones(n) Generates an n-by-n matrix with all elements are
ones.
>> x=n0 : st : nf Generates a vector starting by n0 and ends by nf with
steps=st.
>> x = rand randn Generates a random value x
>> x = rand(1,n) randn(1,n) Generates a random vector x with dimensions (1xn)
>> x = rand(m,n) randn(m,n) Generates a random matrix x with dimensions (mxn)
>> x = linspace(n1,n2) Generates a row vector of 100 linearly equally spaced
points between n1 and n2.
>> x = linspace(n1,n2,m) Generates a row vector of (m) linearly equally spaced
points between n1 and n2.
>> x = linspace(-pi,pi,4) Generates a vector x of four elements linearly
spaced
>> x = logspace(n1,n2) Generates a row vector of 50 logarithmically equally
spaced points between decades 10^n1 and 10^n2.
If n2 is pi, then the points are between 10^n1 and pi
>> x = logspace(n1,n2,m) Generates a row vector of (m) logarithmically equally
spaced points between decades 10^n1 and 10^n2.
If n2 is pi, then the points are between 10^n1 and pi

>> I = FIND(X) Returns the indices of the elements in vector X that


are non-zero
>> I = FIND(X>20) Returns the indices of the elements in vector X that
are greater than 20
>> [I,J] = FIND(A>20) Returns the row and column indices of the elements
in matrix A that are greater than 20.
This is often used with sparse matrices
>> [I,J,v] = FIND(A>20) Returns the row and column indices of the elements
in matrix A that are greater than 20.
This is often used with sparse matrices

Mat1-13-sessions
233
G.A. El-Sheikh MATLAB: Introductory Course 234

 Subscripting:
>> x = A(n1,n2) Returns the value of the element
(n1xn2) in matrix A.

>> x = A(n1 : n2, :) Returns the values of the rows (n1 :


n2) from the matrix A.
1 2 3 4 5
23 12 23 3 10
41 78 11 45 30
56 67 18 55 39
70 33 90 78 15
A(2 : 3 , : )

>> x = A(: , n1 : n2 ) Returns the values of the columns


(n1 : n2) from the matrix A.
1 2 3 4 5
23 12 23 3 10
41 78 11 45 30
56 67 18 55 39
70 33 90 78 15
A(: , 3 : 4)

>> x = A(m1 : m2 , n1 : n2 ) Returns the values of the elements in


the rows (m1 : m2) and columns (n1
e.g. : n2) from the matrix A.
m1=2
1 2 3 4 5
m2=4
23 12 23 3 10
n1=3
n2=4 41 78 11 45 30
56 67 18 55 39
70 33 90 78 15
A(2 : 4 , 3 : 4)

>> x = A(v1 , v2 ) v1 and v2 are vectors with integer


components.
Returns a matrix obtained by taking
the elements of the matrix A with
row subscripts from v1 and column
subscripts from v2.

Mat1-13-sessions
234
G.A. El-Sheikh MATLAB: Introductory Course 235

v2 = [5 3 2 ]
10 23 12 1 2 3 4 5
v1 = [2 4 1 ] 39 18 67 23 12 23 3 10
5 3 2 41 78 11 45 30
56 67 18 55 39
70 33 90 78 15
A(v1 , v2)
>> A( : , [n1 n2] ) = [] Deletes the columns n1 and n2 from the matrix A.
>> A( : , [n1 n2] ) = [] Deletes the columns n1 and n2 from the matrix A.

>> x = diag (A) Returns the diagonal elements of the matrix A.

>> x = tril (A) Returns the lower triangular matrix from the elements
in the lower part of the matrix A.
>> x = tril (A, n) Returns the lower triangular matrix from the elements
below the n-th diagonal of the matrix A.
n=0 means the main diagonal
n>0 means above the main diagonal
n<0 means below the main diagonal

>> x = triu (A) Returns the upper triangular matrix from the elements
in the upper part of the matrix A.
>> x = triu (A, n) Returns the upper triangular matrix from the elements
above the n-th diagonal of the matrix A.
n=0 means the main diagonal
n>0 means above the main diagonal
n<0 means below the main diagonal

 Data Analysis:
>> x = max (A) Returns a vector containing the maximum value for
each column in the matrix A.

>> x = min (A) Returns a vector containing the minimum value for
each column in the matrix A.
>> mu = mean (A) Returns a vector containing the mean value for each
column in the matrix A.
>> sigma = std (A) Returns a vector containing the standard deviation
value for each column in the matrix A.

>> I = find(isnan(x)) Returns a vector containing the indices of the non-


arithmatic numbers (NaN) in the vector x.
>> x = x (find(~isnan(x))) Returns the data in x with the NaNs removed.
or

Mat1-13-sessions
235
G.A. El-Sheikh MATLAB: Introductory Course 236

>> x = x (~isnan(x))
or
>> x (isnan(x)) = []
>> x (any(isnan(x)’) , : ) = []; Returns the data in x with the rows containing
NaNs are removed.

 Removing outliers in measured data:

>> [m, n] = size (A) Returns the number of rows (m) and number
of columns (n) for the data matrix A.
>> e = ones (m , 1) Returns a vector of m- ones.
>> mu = mean (A) Returns a vector containing the mean value
for each column in the data matrix A.
>> sigma = std (A) Returns a vector containing the standard
deviation value for each column in the data
matrix A.
>> outliers = abs (A-e*mu) > 3*e*sigma; Returns the number of rows with outliers
greater than 3 times the standard deviations.
>> nout = sum(outliers)
>> A(any(outliers’) , : ) = []; Removes the entire outliers in the data matrix
A.

>> P = poly (A) Returns the coefficients for the Characteristic


Equation of the Matrix A.
>> R = roots(P) Returns the roots for the Characteristic
Equation of the Matrix A.
>> P2 = poly(R) Returns back the Characteristic Equation of
the Matrix A.
>> Pc = conv(p1, p2) Returns the product of the two polynomials
p1 and p2 which is the convolution of their
coefficients.
DECONV Deconvolution and polynomial division
>> [p1, r] = deconv(Pc, p2) Returns the polynomial p1 by dividing Pc by
the polynomial p2 . (r) is the remainder of the
division process.
Deconvolves vector p2 out of vector Pc. The
result is returned in vector p1 and the
remainder in vector r such that Pc =
conv(p1,p2) + r.
If p2 and p1 are vectors of polynomial
coefficients, deconvolution is equivalent to
polynomial division. The result of dividing Pc
by p2 is quotient p1 and remainder r.

Mat1-13-sessions
236
G.A. El-Sheikh MATLAB: Introductory Course 237

 Plotting:

>> plot(x,y) Plots vectors or matrices (y versus x) i.e.

Plots vector X versus vector Y. If X or Y is a


matrix, then the vector is plotted versus the
rows or columns of the matrix, whichever line
up.
>> plot(y) Plots the columns of Y versus their index.

If Y is complex, PLOT(Y) is equivalent to


PLOT(real(y), imag(y).
>> PLOT(X,Y,S) Plots vector X versus vector Y with Various
line types, plot symbols and colors where S is
a 1, 2 or 3 character string made from the
following characters:

Colour Line type & Symbols


y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green - solid
b blue * star
w white : dotted
k black -. dashdot
-- dashed

The PLOT command, if no color is specified, makes automatic use of the colors specified by the axes
Color Order property. The default Color Order is listed in the table above where the default is
yellow for one line, and for multiple lines, to cycle through the first six colors in the table.

>> PLOT(X,Y, 'c+') Plots vector X versus vector Y with a cyan


plus at each data point.
>> PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) Combines the plots defined by the (X,Y,S)
triples, where the X's and Y's are vectors or
matrices and the S's are strings

>> PLOT(X,Y,'y-',X,Y,'go') Plots the data twice, with a solid yellow line
interpolating green circles at the data points.

>> PLOT3 Plot lines and points in a three-dimensional (3-


D) space
>> PLOT3(x,y,z) Plots a line in 3-D space through the points whose
coordinates are the elements of x, y and z , where
x, y and z are three vectors of the same length.
>> PLOT3(X,Y,Z) Plots several lines in 3-D space through the

Mat1-13-sessions
237
G.A. El-Sheikh MATLAB: Introductory Course 238

points obtained from the columns of X, Y and


Z, where X, Y and Z are three matrices of the
same size.
>> PLOT3(X,Y,Z,s) Plots several lines in 3-D space through the
points obtained from the columns of X, Y and
Z, where X, Y and Z are three matrices of the
same size.
with various line types, plot symbols and
colors due to s which is a 1, 2 or 3 character
string made from the characters listed under
the PLOT command.

>> PLOT3(x1,y1,z1,s1,x2,y2,z2,s2,x3,y3,z3,s3,...) Combines the plots defined by the (x,y,z,s)


fourtuples, where the x's, y's and z's are
vectors or matrices and the s's are strings.

Example: A helix

>> t = 0 : pi/50 : 10*pi;


Plots A circle in 2-D space through the
>> plot3(sin(t),cos(t)), grid points obtained from the columns of :
(sin t), and (cos t).
>> plot3(sin(t),cos(t),t), grid
>> title ( ` A helix `) Plots A helix in 3-D space through the
>> xlabel ( ` X = sin t `) points obtained from the columns of :
>> ylabel (` Y = cos t ` ) (sin t), (cos t) and t.
>> zlabel ( ` Z = t `)

>> SUBPLOT(m,n,p), or SUBPLOT Create axes in tiled positions.

>> SUBPLOT(mnp), Breaks the Figure window into an m-by-n matrix


of small axes, selects the p-th axes for for the
current plot, and returns the axis handle. The axes
are counted along the top row of the Figure
window, then the second row, etc.

If a SUBPLOT specification causes a new axis to overlap an existing axis, the existing axis is
deleted. For example, the statement SUBPLOT(1,1,1) deletes all existing smaller axes in the
Figure window and creates a new full-figure axis.

>> SUBPLOT(2,1,1), PLOT(X) Plots X on the top half of the window


and Y on the bottom half.
>> SUBPLOT(2,1,2), PLOT(Y)

Mat1-13-sessions
238
G.A. El-Sheikh MATLAB: Introductory Course 239

Control Flow:
The MATLAB has control flow statements like those found in most of the high level
programming languages.

1- FOR Loops
This command allows a statement or a group of statements to be repeated a fixed,
predetermined number of times.

FOR Repeat statements a specific number of times. The


general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END


FOR I = 1:N,
FOR J = 1:N, The columns of the expression are stored one at a time
A(I,J) = 1/(I+J-1); in the variable and then the following statements, up to
END the END, are executed. The expression is often of the
END form X:Y, in which case its columns are simply scalars.
Some examples (assume N has already been assigned a
value).
FOR E = EYE(N), Sets the variable E to the unit N-vectors and repeats or
Expression calculates the expression N-times.
END

2- WHILE Loops
This command allows a statement or a group of statements to be repeated an indefinite
number of times, under control of a logical condition.

WHILE Repeat statements an indefinite number of times.

WHILE variable, The general form of a WHILE.


statement, ..., statement,
END The statements are executed while the variable has all non-
zero elements. The variable is usually the result of expr rop
expr where
rop is ==, <, >, <=, >=, or ~=.

A = [1 2 3; 4 5 6; 7 8 9]; A is the given matrix


E = 0*A; E is the desired exponential
F = E + EYE(E); F is an individual term in the series
N = 1; N is the index of that term
WHILE NORM(E+F-E,1) > 0,
E = E + F; This segment gives the exponential of the given matrix i.e.
F = A*F/N;
N = N + 1; = expm(A)
END
OR
A = [1 2 3; 4 5 6; 7 8 9] ;
E = zeros(size(A));

Mat1-13-sessions
239
G.A. El-Sheikh MATLAB: Introductory Course 240

F = EYE(size(A));
N = 1;
WHILE NORM(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
END
Where;
EXPM Matrix exponential

EXPM is computed using a scaling and squaring


EXPM(A)=I+A+A^2/2!+A^3/3!+…. algorithm with a Pade approximation. Although
it is not computed this way, if X has a full set of
eigenvectors V with corresponding eigenvalues
D, then [V,D] = EIG(X) and
EXPM(X) = V*diag(exp(diag(D)))/V.

NORM Is the Matrix or vector norm


For matrices
NORM(X) is the largest singular value of X, max(svd(X)).
NORM(X,2) is the same as NORM(X).
NORM(X,1) is the 1-norm of X, the largest column sum, =max(sum(abs((X)))).
NORM(X,inf) is the infinity norm of X, the largest row sum, =
max(sum(abs((X')))).
NORM(X,'inf') is same as NORM(X,inf).
NORM(X,'fro') is the F-norm, sqrt(sum(diag(X'*X))).
NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'

For vectors
NORM(V,P) = sum(abs(V)^P)^(1/P).
NORM(V) = norm(V,2).
NORM(V,inf) = max(abs(V)).
NORM(V,-inf) = min(abs(V)).

3- If and BREAK Statements


IF Conditionally execute statements
The general form of an IF statement where:
IF variable, The statements are executed if the real part of the variable has all
statements, non-zero elements. The variable is usually the result of expr rop
END expr where rop is ==, <, >, <=, >=, or ~=.
IF I == J
A(I,J) = 2;
ELSEIF ABS(I-J) == 1
A(I,J) = -1;
ELSE
A(I,J) = 0;
END

Mat1-13-sessions
240
G.A. El-Sheikh MATLAB: Introductory Course 241

WHILE 1 Enter any positive integer


N=INPUT(‘ ENTER N, QUITS FOR number
NEGATIVE’);
IF N<= 0, BREAK, END If it is even, divide by 2
WHILE N > 1
IF REM(N,2) == 0 If it is odd multiply it by 3 and
N = N/2; add 1
ELSE
N = 3*N+1; Repeat this process until your
END integer becomes a 1.
END
END

M-Files: Scripts and Functions


MATLAB is usually used in a command-driven mode, when you enter single-line commands,
the MATLAB process them immediately and displays the results. In addition, it can execute
sequences of commands that are stored in files called m-files, the name of which has an
extension .m. This type of files is called by its name (without the extension) from the
MATLAB command window and it is edited using any text/ascii editor.

The m-files may be scripts or functions. The scripts (script files) automate long sequences of
commands. While, the functions (function files) are used to provide extensibility to MATLAB.
In addition, they allow to add new functions to the existing functions.

1- Script Files:
A SCRIPT file is an external file that contains a sequence of MATLAB statements. By typing
the filename, subsequent MATLAB input is obtained from the file. SCRIPT files have a
filename extension of ".m" and are often called "M-files".

For Example: The Fibonacci numbers can be obtained as follows


1000

f=[1 1]; 900

i = 1; 800

while f(i)+f(i+1) < 1000 700

f(i+2) = f(i) + f(i+1); 600

i = i + 1; 500

end 400

plot(f,'linewidth',3), grid on 300

200

100

0
0 2 4 6 8 10 12 14 16

2- Function Files:
New functions may be added to MATLAB's vocabulary if they are expressed in terms of other
existing functions. The commands and functions that comprise the new function must be put in
a file whose name defines the name of the new function, with a filename extension of '.m'. At

Mat1-13-sessions
241
G.A. El-Sheikh MATLAB: Introductory Course 242

the top of the file must be a line that contains the syntax definition for the new function. For
example, the existence of a file on disk called STAT.M with:

function [mean,stdev] = stat(x) Defines a new function called STAT that calculates
n = length(x); the mean and standard deviation of a vector. The
mean = sum(x) / n; variables within the body of the function are all local
stdev = sqrt(sum((x - mean).^2)/n); variables. (stat.m)

function r = rank(x,tol) RANK Number of linearly independent rows or


columns.
s = svd(x); K = RANK(X) is the number of singular values of X
if (nargin == 1) that are larger than MAX(SIZE(X)) * NORM(X) *
tol = max(size(x)) * max(s) * eps; EPS. K = RANK(X,tol) is the number of singular
end values of X that are larger than tol.
r = sum(s > tol);

EVAL Execute string containing MATLAB expression.


EVAL(s), where s is a string, causes MATLAB to execute the
string as an expression or statement.
EVAL(s1,s2) provides the ability to catch errors. It executes string
s1 and returns if the operation was successful. If the
operation generates an error, string s2 is evaluated
before returning.
EVAL('try','catch')
[X,Y,Z,...] = EVAL(s) Returns output arguments from the expression in
string s.
The input strings to EVAL are often created by
concatenating substrings and variables inside square
brackets.

for n = 1:12 Generate a sequence of matrices named M1 through


eval(['M' num2str(n) ' = magic(n)']) M12
end

D = ['odedemo ' Run a selected M-file script. The strings making up


'quaddemo' the rows of matrix D must all have the same length.
'fitdemo '];
n = input('Select a demo number: ');
eval(D(n,:))
k = 0; Read and process files with names data1.dat,
while 1 data2.dat, ...
k = k+1;
datak = ['data' int2str(k)];
filename = [datak '.dat'];
if ~exist(filename), break, end
eval(['load ' filename]);
X = eval(datak);
% Process data in matrix X.

Mat1-13-sessions
242
G.A. El-Sheikh MATLAB: Introductory Course 243

end

Mat1-13-sessions
243
G.A. El-Sheikh MATLAB: Introductory Course 243

14- Real World Applications


In any problem solution, you should make sure the vertical and horizontal axes of your graph are
properly labeled, and the plot has a suitable title. Your m-file should contain comment statements
identifying the author, the purpose of the m-file, and a description of the variables and
arrays/variables used in the problem solution.

14.1 Example-14.1: Temperature Conversion


Problem Statement: The relationship between temperature measured in Fahrenheit ( Tf ) and
temperature Celsius ( Tc ) is given by the following equation:
9
Tf  Tc  32
5
Write an m-file that computes and plots the temperature conversion relationship over the range -
50 through 100 degrees Celsius. You should make sure the vertical and horizontal axes of your
graph are properly labeled, and the plot has a suitable title. Your m-file should contain comment
statements identifying the author, clarifying the problem, the purpose of the m-file, and a
description of the variables and arrays used in the problem solution.

Problem Solution: Here is an m-file containing a first trial solution (exheat1.m and
exheat2.m):
%*************************************************************************
%*** exheat2.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used for Temperature Conversion from Celcius to ***
%*** Fahrenheit covering the range T1 through T2 degrees Celcius. ***
%*************************************************************************
clc
clear

T1 = input(' The minmum value of temperature to be converted T1: ');


T2 = input(' The maximum value of temperature to be converted T2: ');

Temp1 = [];
Num = abs(T1) + T2 + 1; Fahrenheit versus Celcius Temperature Conversion
250
for i = 1 : Num;
Temp1(i,1) = i -(abs(T1)+1); 200
Temp1(i,2) = 9*Temp1(i,1)/5 + 32;
end 150
Temperature [Fahrenheit]

plot(Temp1(:,1), Temp1(:,2)); 100


grid;
xlabel('Temperature [Celcius]'); 50
ylabel('Temperature [Fahrenheit]');
title('Fahrenheit versus Celcius
0
Temperature Conversion');
-50
The result obtained by this m-file is shown in Fig.
14.1. -100
-50 0 50 100
Temperature [Celcius]

Fig. 14.1: Fahrenheit versus Celcius


Temperature Conversion

Mat1-14-real-apps
243
G.A. El-Sheikh MATLAB: Introductory Course 244

Comments: The following points can be drawn from this example:


 The first and second columns of matrix "Temp1" store the temperature in Celsius and
Fahrenheit, respectively.
 In the plot command:
plot(Temp1(:,1), Temp1(:,2));
the data points in column one of matrix "Temp1" are plotted against the data points in
column two of "Temp1" .
 The temperature arrays can also be constructed by using colon notation and matrix-element
operations. For example, the command
TempC = [ T1 : T2 ] = [ -50:100 ];
will define a one-dimensional array of 151 elements initialized to -50 through 100. A
corresponding array of temperatures in Fahrenheit can be assembled by simply writing
TempF = TempC*(5/9) + 32; % Arithmetic operations
with vectors
The slightly modified plot command is:
plot(TempC, TempF)

Mat1-14-real-apps
244
G.A. El-Sheikh MATLAB: Introductory Course 245

14.2 Example-14.2:
Free Vibration Response of Undamped SDOF System
Problem Statement: The time-history free vibration response of an undamped single-degree
of freedom oscillator is given by:
V(0)
X( t )  X(0) cos( t )  sin ( t )

where
t time.
x(t) displacement at time t.
v(t) velocity at time t.
w
K/m
circular natural frequency of the system.
m the system mass.
k the system stiffness.
The natural period of this system is
T  2 m/k
Now let's suppose that the system has mass = 1, stiffness = 10, and an initial displacement and
velocity x(0) = 10 and v(0) = 10.

Write a MATLAB m-file that will compute and plot the "displacement versus time" (i.e., x(t)
versus t) and "velocity versus time" (i.e., v(t) versus t) for the time interval 0 through 10 seconds.
To ensure that your plot will be reasonable smooth, choose an increment in your displacement
and velocity calculations that is no larger than 1/10 of the system period T.

Solution: As a first trial, the following m-file can carry on the solution:
%*************************************************************************
%*** exsdof2.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used to calculate the dynamic response of SDOF ***
%*** system. ***
%*************************************************************************
clc
clear

% Setup array for storing and plotting system response


Np = 501;
resp1 = [];

% Problem parameters and initial conditions


mass = 1;
stiff = 10;
w = sqrt(stiff/mass);
dt = 0.02;
D0 = 1;
V0 = 10;

% Compute displacement and velocity time history response

for i = 1 : Np + 1
Time1 = (i-1)*dt;
resp1(i,1) = Time1;
resp1(i,2) = D0*cos(w*Time1) + V0/w*sin(w*Time1);
resp1(i,3) = -D0*w*sin(w*Time1) + V0*cos(w*Time1);
end

Mat1-14-real-apps
245
G.A. El-Sheikh MATLAB: Introductory Course 246

% Plot displacement and velocity versus time

plot(resp1(:,1), resp1(:,2:3));

grid;
xlabel(' Time [sec]');
ylabel(' Displacement [m] (blue) and Velocity [m/sec] (red)');
title (' Time-History Response for SDOF Oscillator');
legend('Displacement', 'Velocity', 0)
Time-History Response for SDOF Oscillator
The graphical output is: 15

10

5
Output

-5

-10
Displacement [m]
Velocity [m/sec]
-15
Comments: Points to note are: 0 2 4 6 8 10 12
Time [sec]
 The velocity of the SDOF system
versus time is given by the derivative Fig. 14.2: Time-History Response of SDOF Oscillator
of the displacement with respect to
time. In mathematical terms:
d
v( t ) 
x ( t )   x o  sin ( t )  v o cos( t )
dt
where x o and v o are the displacement and velocity of the system at t = 0.
 The natural period of this system is
T  2  k / m  6.282 / 10  2 [sec]
 The time-step increment dt = 0.02 seconds easily satisfies the stated criteria for a smooth graph.
 The first column of response stores the time, and the second and third columns of response the
displacement and velocity, respectively.
 A second way of computing the time, displacement, and velocity vectors is
time = 0.0:0.02:10;
displ = displ0*cos(w*time) + velocity0/w*sin(w*time);
velocity = -displ0*w*sin(w*time) + velocity0*cos(w*time);
The first statement generates a (1x501) matrix called time having the element values 0, 0.02, 0.04 ....
10.0. The dimensions of matrices "displ" and "velocity" are inferred from the dimensions of "temp" with
the values of the matrix elements given by the evaluation of formulae on the right-hand side of the
assignment statements.
Now the plots can be generated with:
plot(time, displ);
hold;
plot(time, velocity);
 So how do we know that these graphs might be correct? First, notice that at t = 0 seconds,
the displacement and velocity graphs both match the stated initial conditions. Second,
note that because the initial velocity is greater than zero, we expect the displacement

Mat1-14-real-apps
246
G.A. El-Sheikh MATLAB: Introductory Course 247

curve to initially increase. It does. A final point to note is the relationship between the
displacement and velocity. When the oscillator displacemnt is at either its maximum or
minimum value, the mass will be at rest for a short time. In mathematical terms, peak
values in the displacement curve correspond to zero values in the velocity curve.

14.3 Example-14.3:
Statistical Analysis of Experimental Data
Problem Statement: Suppose that the concentration of spores of pollen per squared cm are
measured over a 15 day period, and stored in a data file ex3data.dat.
1 12
2 35
3 80
4 120
5 280
6 290
7 360
8 290
9 315
10 280
11 270
12 190
13 90
14 85
15 66
The first and second columns of ex3data.dat represent the "day of the experiment" and the
"measured pollen count", respectively.

Write a MATLAB program that will:


1. Read the contents of the data file into an array.
2. Create a two-dimensional bar plot showing the "pollen count" versus "day"
3. Compute the mean and standard deviation of the pollen count for the duration of the
experiment.
4. Plot and label dashed-lines of the mean pollen count plus and minus one standard
deviation.

Solution: The following m-file can carry on the required solution:


%*************************************************************************
%*** exstat1.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used to analyze experimental data collected and ***
%*** stored in a data file ex3data.dat. ***
%*************************************************************************
clc
clear

%*** Load data file and store experimental results in array


load ex3data.dat

%*** Generate bar plot of experimental results


bar(ex3data(:,1), ex3data(:,2),'b'), grid
xlabel('Day of Experiment');
ylabel('Pollen Count');

%*** Compute terms from experimental results.

Mat1-14-real-apps
247
G.A. El-Sheikh MATLAB: Introductory Course 248

xm = mean(ex3data(:,2));
xd = std(ex3data(:,2));

%*** Create and display mean value of pollen count


mean_minus = xm(1,1) - xd(1,1);
mean_plus = xm(1,1) + xd(1,1);

data = [ 1, xm(1,1), mean_minus, mean_plus;


15, xm(1,1), mean_minus, mean_plus ];

hold;
plot (data(:,1), data(:,2), 'b');
plot (data(:,1), data(:,3), 'b:');
plot (data(:,1), data(:,4), 'b:');

text(1, xm(1,1) + 10,'Mean Pollen Count');


text(1,mean_minus + 10,'Mean - Std');
text(1, mean_plus + 10,'Mean + Std');

Running this program generates the 400

textual output: 350


>> expt
Mean + Std
300
xm =
184.2000
250
Pollen Count

xd =
200
114.2309 Mean Pollen Count

>>
150
and the graphical output:
100
Mean - Std
50

0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Day of Experiment

Fig. 14.3: Pollen Count versus Day of Experiment

Comments:
 The solution to this problem takes advantage of data files, and other user-defined functions
located in the same working directory.
More precisely, the command:
load ex3data.dat;
loads the content of datafile "ex3data.dat" into the array " ex3data ". Then the
commands:
xm = mean(ex3data(:,2))
xd = std(ex3data(:,2))
compute the mean and standard deviation of data stored in the second column of
ex3data. In addition, a user-defined function can be defined and called within the main
program to calculate the required statistical data.

Mat1-14-real-apps
248
G.A. El-Sheikh MATLAB: Introductory Course 249

14.4 Example-14.4:
Least Squares Analysis of Geological Borings
Problem Statement: Figure 14.4 is a three-dimensional view of a 2 km by 2 km site that is
believed to overlay a thick layer of mineral deposits.

Fig. 14.4: Three-Dimensional


View of Mineral Deposits

To create a model of the mineral deposit profile and establish the economic viability of mining
the site, a preliminary subsurface exploration consisting of 16 bore holes is conducted. Each bore
hole is drilled to approximately 45 m, with the upper and lower boundaries of mineral deposits
being recorded. The bore hole data is as follows:

Borehole [ x, y ] coordinate [ upper, lower ] mineral surfaces


====================================================================
1 [ 10.0 m, 10.0 m ] [ -30.5 m, -40.5 m ]
2 [ 750.0 m, 10.0 m ] [ -29.0 m, -39.8 m ]
3 [ 1250.0 m, 10.0 m ] [ -28.0 m, -39.3 m ]
4 [ 1990.0 m, 10.0 m ] [ -26.6 m, -38.5 m ]
5 [ 10.0 m, 750.0 m ] [ -34.2 m, -41.4 m ]
6 [ 750.0 m, 750.0 m ] [ -32.8 m, -40.6 m ]
7 [ 1250.0 m, 750.0 m ] [ -31.8 m, -40.1 m ]
8 [ 1990.0 m, 750.0 m ] [ -30.3 m, -39.4 m ]
9 [ 10.0 m, 1250.0 m ] [ -36.7 m , -42.0 m ]
10 [ 750.0 m, 1250.0 m ] [ -35.2 m, -41.2 m ]
11 [ 1250.0 m, 1250.0 m ] [ -34.2 m, -40.7 m ]
12 [ 1990.0 m, 1250.0 m ] [ -32.8 m, -40.0 m ]
13 [ 10.0 m, 1990.0 m ] [ -40.4 m, -42.8 m ]
14 [ 750.0 m, 1990.0 m ] [ -39.0 m, -42.1 m ]
15 [ 1250.0 m, 1990.0 m ] [ -38.0 m, -41.6 m ]
16 [ 1990.0 m, 1990.0 m ] [ -36.5 m, -40.9 m ]

With the borehole data collected, the next step is to create a simplified three-dimensional
computer model of the site and subsurface mineral deposits. The mineral deposits will be
modeled as a single six-sided object. The four vertical sides are simply defined by the boundaries
of the site. The upper and lower sides are to be defined by a three-dimensional plane,
z ( x , y)  a 0  a 1 x  a 2 y

Mat1-14-real-apps
249
G.A. El-Sheikh MATLAB: Introductory Course 250

where coefficients ao, a1, and a2 correspond to minimum values of


N
S(a 0 , a 1 , a 2 )   z i  z( x i  y i )
2

i 1

Things to do:
1. Show that minimum value of S( ao, a1, a2) corresponds to the solution of a family of
(3x3) matrix equations
2. Write a matlab m-file that will create three-dimensional plots of the borehole data at the
lower and upper surfaces. See the matlab function griddata().
3. Write a matlab m-file that will setup and solve the matrix equations derived in part 1 for
the upper and lower mineral planes.
4. Compute and print the average depth and volume of mineral deposits enclosed within the
site.
Note : You should find that the equation of the upper surface is close to
z(x,y) = -30.5 + x/500 - y/200
and lower surface close to
z(x,y) = -40.5 + x/1000 - y/850.

Solution: The least squares solution corresponds to the minimum value of function S( ao, a1, a2). At the
minimum function value, we will have
dS dS dS
---- = ---- = ---- = 0.0
da_o da_1 da_2
In matrix form, the three three equations with three unknowns are:
*- -* *- -* *- -*
| N sum_X sum_Y | | a_o | | sum_Z |
| | | | | |
| sum_X sum_X.X sum_X.Y |.| a_1 | = | sum_X.Z |
| | | | | |
| sum_Y sum_X.Y sum_Y.Y | | a_2 | | sum_Y.Z |
*- -* *- -* *- -*
where sum_X is the sum of the X coordinate values, sum_XY is the sum of the product of X.Y coordinate values,
and so forth.

The m-file:
%*************************************************************************
%*** exgeog1.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used to analyse Geological Borings following the ***
%*** Least Squares approach. ***
%*************************************************************************
clc
clear
clf

%*** Define matrix A for geological borings information


A = [ 10.0 10.0 -30.5 -40.5
750.0 10.0 -29.0 -39.8
1250.0 10.0 -28.0 -39.3
1990.0 10.0 -26.6 -38.5
10.0 750.0 -34.2 -41.4
750.0 750.0 -32.8 -40.6
1250.0 750.0 -31.8 -40.1
1990.0 750.0 -30.3 -39.4
10.0 1250.0 -36.7 -42.0

Mat1-14-real-apps
250
G.A. El-Sheikh MATLAB: Introductory Course 251

750.0 1250.0 -35.2 -41.2


1250.0 1250.0 -34.2 -40.7
1990.0 1250.0 -32.8 -40.0
10.0 1990.0 -40.4 -42.8
750.0 1990.0 -39.0 -42.1
1250.0 1990.0 -38.0 -41.6
1990.0 1990.0 -36.5 -40.9 ];

%*** Compute terms in matrix BB and right-hand vectors


N = 16;
sumx = sum(A(:,1));
sumy = sum(A(:,2));
sumx2 = sum(A(:,1).*A(:,1));
sumy2 = sum(A(:,2).*A(:,2));
sumxy = sum(A(:,1).*A(:,2));

BB = [ N sumx sumy
sumx sumx2 sumxy
sumy sumxy sumy2 ]

sumzt = sum(A(:,3));
sumzb = sum(A(:,4));
sumzty = sum(A(:,3).*A(:,2));
sumzbx = sum(A(:,4).*A(:,1));
sumzby = sum(A(:,4).*A(:,2));
sumztx = sum(A(:,3).*A(:,1));

DT = [sumzt; sumztx; sumzty];


DB = [sumzb; sumzbx; sumzby];

%*** Compute constants a,b,c


B = inv(BB);
CT = B*DT
CB = B*DB

%*** Compute average depth and volume


x = 1000;
y = 1000;

zt = CT(1,1)+(x*CT(2,1))+(y*CT(3,1));
zb = CB(1,1)+(x*CB(2,1))+(y*CB(3,1));

avedepth = abs(zb-zt)
volume = avedepth*(2000)^2

%*** Plot top and bottom mineral surfaces

[x y] = meshgrid(0:10:2000,0:10:2000);
zb = CB(1,1)+(x*CB(2,1))+(y*CB(3,1));
mesh(x,y,zb)
hold on;
[x y] = meshgrid(0:10:2000,0:10:2000);
zt = CT(1,1)+(x*CT(2,1))+(y*CT(3,1));
mesh(x,y,zt), grid on
title('Mineral Deposit')
xlabel('Width')
ylabel('Length')
zlabel('Depth')
text(500,1750,-20,'Average Depth = 7.1812 Volume = 2.8725e+07')
hold off

generates the output:

Mat1-14-real-apps
251
G.A. El-Sheikh MATLAB: Introductory Course 252

BB =

16 16000 16000
16000 24340800 16000000
16000 16000000 24340800

CT =
-30.4538
0.0020
-0.0050

CB =
-40.5031
0.0010
-0.0012

avedepth =
7.1812

volume =
2.8725e+07

In addition, a three dimensional graphic of the mineral deposit boundaries;

Fig. 14.4b: Upper- and Lower- Layers of Mineral Deposits


Comments:
 Matrices CB and CT contain the coefficients for the least squares equations representing the
lower and upper mineral plane surfaces. You should observe that the coefficients are very
close to the equations mentioned in the problem statement.
 The most straight forward way of computing the sum of product terms in matrix A, e.g.,
A(1,4)*A(1,2) + A(2,4)*A(2,2) + .... + A(16,4)*A(16,2)
is with blocks of matlab statements:
sumzby = 0.0;
for i=1:16
sumzby = sumzby + A(i,4)*A(i,2);

Mat1-14-real-apps
252
G.A. El-Sheikh MATLAB: Introductory Course 253

end
The same numerical result can be obtained via matlab's sum() function combined with the
multiply matrix-element operator.
sumzby = sum(A(:,4).*A(:,2));
In fact, it is possible to completely eliminate the variable "sumzby" from the calculation,
and form the (3x3) least squares matrix in one block of statements:
BB = [ 16 sum(A(:,1)) sum(A(:,2));
sum(A(:,1)) sum(A(:,1).*A(:,1)) sum(A(:,1).*A(:,2));
sum(A(:,2)) sum(A(:,1).*A(:,2)) sum(A(:,2).*A(:,2)) ]
Similar expressions can be written for matrices "DB" and "DT".
 The average depth of mineral deposits is simply the difference in "z" coordinates at (x,y)
= (1000,1000). And the volume of mineral deposits is simply the cross section area --
2000x2000 m^2 -- times the average depth.

Mat1-14-real-apps
253
G.A. El-Sheikh MATLAB: Introductory Course 254

14.5 Example-14.5:
Steady State Temperature in a Chimney Cross Section
Problem Statement: Figure 14.5 shows the front elevation and square-shaped cross section
A-A for the tall chimney.

Fig. 14.5: Front Elevation and Cross Section of Tall Chimney

The chimney is constructed from a material that is homogeneous and isotropic (i.e., the material
has the same material properties in all directions). At the cross section, the inside and outside
temperatures are 200 degrees Centigrade and 0 degrees Centigrade, respectively, and there is
neither a net flow of heat to, or from, the chimney (i.e., the chimney is in thermal equilibrium).
Finally, we will assume that at the chimney cross-section, the distribution of temperature is
constant along the z-axis. Because the chimney is constructed from a material that is
homogeneous, thermal conductivity will not vary with position, and because the material is
isotropic, thermal conductivity will not vary with direction. The steady state distribution of
temperature
T = T(x,y)
throughout the chimney cross section is given by solutions to Laplace's equation
d^2 T(x,y) d^2 T(x,y)
========== + ========== = 0.0
dx^2 dy^2
with boundary conditions T = 0 degrees Centigrade along the exterior of the chimney, and T =
200 degrees Centigrade along at the chimney interior,

Mat1-14-real-apps
254
G.A. El-Sheikh MATLAB: Introductory Course 255

Fig, 14.5b: Finite Difference Mesh

The chimney cross-section is symmetric about the x- and y- axes, and the two diagonal axes. In
our computational model, we will take advantage of symmetries about the x- and y-axes by
modeling only one quarter of the chimney cross section, as shown in Figure 3. Two new
boundary conditions are needed for this model -- along the y axis the temperature gradient
dT/dx = 0,
and along x axis
dT/dy = 0.
If dx and dy are the mesh distance in the x and y axis directions, a suitable finite difference approximation to
Laplace's equation is
T(x+dx,y) - 2T(x,y) + T(x-dx,y) T(x,y+dy) - 2T(x,y) + T(x,y-dy)
=============================== + =============================== =
0.0
dx^2 dy^2
When dx = dy our finite difference equation can be rearranged to give
4 T{(x,y)} - T(x-dx,y) - T(x+dx,y) - T(x,y+dy) - T(x,y-dy) = 0.

Mat1-14-real-apps
255
G.A. El-Sheikh MATLAB: Introductory Course 256

Fig. 14.5c: Finite Difference Stencils

The left-most schematic of Figure 4 shows the weighting of discrete temperatures in the finite
difference approximation. The nodes along the x axis (i.e., y = 0) satisfy the finite difference
equation
4 T(x,0) - T(x-dx,0) - T(x + dx,0) - 2 T(x,dy) = 0
and along the y axis (i.e., x = 0)
4 T(0,y) - 2 T(dx,y) - T(0,y+dy) - T(x,y-dy) = 0.

The finite difference mesh has 65 nodes, 26 of them being on the interior (i.e., T = O degrees
Centigrade) and exterior (i.e., T = 200 degrees Centigrade) boundaries. This leaves 39 nodes on
the chimney interior for evaluation. Instead of evaluating the temperature stencils at all 39
interior nodes, we compute temperature only at the 21 nodes labeled with small filled-black
boxes, and fill in the remaining unknowns by noting the symmetry in temperature along the line
x = y
The four node stencil is used at nodes 1 to 3, and the five node stencil nodes 4 to 21.
Things to do:
1. Write an m-file that uses the ``method of iteration'' to compute the temperature at the internal nodes.
2. Create a 2-dimensional color contour plot of the temperature distribution inside the chimney wall.
3. Write an m-file that sets up the finite difference equations in matrix form, and then computes a solution
by solving A.T = B, where T is the temperature at the internal nodes of the chimney.
4. Create a 3-dimensional color plot of the temperature distribution inside the chimney wall.
Note : You can mimic the hole in the chimney by creating a matrix for 1/4 of the chimney cross section and then
filling relevant matrix items with NaNs.

Solution: The solution to this problem has two parts, first by computing the temperature profile
by iteration, and then by computing the temperature profile by writing and solving the finite
difference equations in matrix form.
Iterative Solution: The m-file for iterative solution is:
%*************************************************************************
%*** extemp1.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used to Compute and displace profiles of temperat-***
%*** ure in chimney cross section following an iterative approach. ***
%*************************************************************************
clc
clear

Mat1-14-real-apps
256
G.A. El-Sheikh MATLAB: Introductory Course 257

% Setup working array and boundary conditions along internal/external


walls.
T = zeros(9,9);

for i = 5:9;
T(i,5) = 200;
end;
for i = 1:5;
T(5,i) = 200;
end;
for i = 6:9;
for j = 1:4;
T(i,j) = NaN;
end;
end;

% Loop over internal nodes and compute new temperatures


counter = 0;
maxchange = 200;
while (maxchange > 1)
counter = counter+1;
maxchange = 0;
k = 5;
l = 4;
for c = 6:8;
newtemp = 0.25*(2*T(l+1,c)+2*T(l,c+1));
tempchange = newtemp - T(l,c);
maxchange = max(maxchange,abs(tempchange));
T(l,c) = newtemp;
for r=k:8
newtemp = 0.25*(T(r,c-1)+T(r,c+1)+T(r-1,c)+T(r+1,c));
tempchange = newtemp - T(r,c);
maxchange = max(maxchange,abs(tempchange));
T(r,c) = newtemp;
end
newtemp = 0.25*(T(9,c-1)+T(9,c+1)+2*T(8,c));
tempchange = newtemp - T(9,c);
maxchange = max(maxchange,abs(tempchange));
T(9,c) = newtemp;
l = l - 1;
k = k - 1;
end
counter;
maxchange; % to view counter or maxchange remove ;
end

% Compute reflected temperature

for i = 2:4
for j = 1: 11-i
T(i,j) = T(10-j,10-i);
end
end

% Print Temperature array.


T

% Plot temperature contours.


contour(T), grid on
hold on;

Mat1-14-real-apps
257
G.A. El-Sheikh MATLAB: Introductory Course 258

% Now overlay perimeter of chimney section on contours.

perim = [ 1 , 1;
9 , 1;
9 , 9;
5 , 9;
5 , 5;
1 , 5;
1 , 1 ];
plot(perim(:,1),perim(:,2),'w');
text(1.1,5.3,'Temp = 200.0');
text(7.0,1.3,'Temp = 0.0');
hold off;

produces the following output:


T =
Columns 1 through 7

0 0 0 0 0 0 0
47.9527 47.4495 45.9241 42.8111 37.2518 28.7560 19.0375
96.9120 96.1208 93.6699 88.3435 77.7632 59.1105 38.4899
147.6536 147.0166 144.9543 139.9098 127.2653 92.5014 59.1105
200.0000 200.0000 200.0000 200.0000 200.0000 127.2653 77.7632
NaN NaN NaN NaN 200.0000 139.9098 88.3435
NaN NaN NaN NaN 200.0000 144.9543 93.6699
NaN NaN NaN NaN 200.0000 147.0166 96.1208
NaN NaN NaN NaN 200.0000 147.6536 96.9120

Columns 8 through 9

0 0
9.3215 0
19.0375 0
28.7560 0
37.2518 0
42.8111 0
45.9241 0
47.4495 0
47.9527 0
The two-dimensional graphic,

Some Comments: Points to note are:


 The first block of code sets up a (9x9) matrix for Fig. 9.5d: Temperature Profile in Chimney
modeling 1/4 of the chimney cross-section. The
temperature along the interior and exterior walls is set to 200 and 0 degrees, respectively.
In Matlab, the interior region of the chimney can be represented with NaNs -- that is a
missing data item.
At this point in the program execution, the contents of matrix T are:
T =
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
200 200 200 200 200 0 0 0 0
NaN NaN NaN NaN 200 0 0 0 0
NaN NaN NaN NaN 200 0 0 0 0
NaN NaN NaN NaN 200 0 0 0 0
NaN NaN NaN NaN 200 0 0 0 0

Mat1-14-real-apps
258
G.A. El-Sheikh MATLAB: Introductory Course 259

The main block of code walks along columns 6 through 8 and evaluates the finite difference stencils for
 Column No Row Nos
 ============================
 6 4 through 9
 7 3 through 9
 8 2 through 9
 ============================
For example, after the algorithm has walked along column 6 for the first time the contents of T are
T =

Columns 1 through 7
0 0 0 0 0 0
0
0 0 0 0 0 0
0
0 0 0 0 0 0
0
0 0 0 0 0 0
0
200.0000 200.0000 200.0000 200.0000 200.0000 50.0000
0
NaN NaN NaN NaN 200.0000 62.5000
0
NaN NaN NaN NaN 200.0000 65.6250
0
NaN NaN NaN NaN 200.0000 66.4062
0
NaN NaN NaN NaN 200.0000 83.2031
0

Columns 8 through 9
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
Bear in mind that the temperature at stencil T(4,6) is still zero because all of the
neighboring stencils are initially zero.
 The three-line blocks of code
 newtemp = 0.25*(T(9,c-1)+T(9,c+1)+2*T(8,c));
 tempchange = newtemp - T(9,c);
 maxchange = max(maxchange,abs(tempchange));
compute the new temperature estimate at the node, the change in noday temperature from
the previous iteration, and the maximum change in temperature occurring over rows 6
through 8 for the current iteration. This algorithm will iterate until the maximum change
in temperature is less than 1 degree.
At the conclusion of the main block of code, the temperature profile is:
T =
Columns 1 through 7
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 38.4899
0 0 0 0 0 92.5014 59.1105

Mat1-14-real-apps
259
G.A. El-Sheikh MATLAB: Introductory Course 260

200.0000 200.0000 200.0000 200.0000 200.0000 127.2653


77.7632
NaN NaN NaN NaN 200.0000 139.9098
88.3435
NaN NaN NaN NaN 200.0000 144.9543
93.6699
NaN NaN NaN NaN 200.0000 147.0166
96.1208
NaN NaN NaN NaN 200.0000 147.6536
96.9120

Columns 8 through 9

0 0
9.3215 0
19.0375 0
28.7560 0
37.2518 0
42.8111 0
45.9241 0
47.4495 0
47.9527 0
The final temperature profile is obtained by reflecting the temperatures along the line y = x.

Matrix Solution: The m-file for matrix solution is:


%*************************************************************************
%*** extemp2.m ***
%*************************************************************************
%*** Author : G.A. El-Sheikh 27-08-2003 ***
%*************************************************************************
%*** This program is used to compute the profile of temperature in the ***
%*** chimney via finite difference matrices, i.e. following the matrix ***
%*** approach. ***
%*************************************************************************
clc
clear

% Define matrix of zeros


A = zeros(21,21);

% Fix non-zero values in matrix


for i=1:21
A(i,i)=4;
end

A(1,2) =-1; A(1,4) =-2;


A(2,1) =-1; A(2,3) =-1; A(2,5)=-2;
A(3,2) =-1; A(3,6) =-2;
A(4,1) =-1; A(4,5) =-1; A(4,7) =-1;
A(5,2) =-1; A(5,4) =-1; A(5,6) =-1; A(5,8)=-1;
A(6,3) =-1; A(6,5) =-1; A(6,9) =-1;
A(7,4) =-1; A(7,8) =-1; A(7,10) =-1;
A(8,5) =-1; A(8,7) =-1; A(8,9) =-1; A(8,11)=-1
A(9,6) =-1; A(9,8) =-1; A(9,12) =-1;
A(10,7) =-1; A(10,11)=-1; A(10,13)=-1;
A(11,8) =-1; A(11,10)=-1; A(11,12)=-1; A(11,14)=-1;
A(12,9) =-1; A(12,11)=-1; A(12,15)=-1;
A(13,10)=-1; A(13,14)=-1; A(13,16)=-1;
A(14,11)=-1; A(14,13)=-1; A(14,15)=-1; A(14,17)=-1;
A(15,12)=-1; A(15,14)=-1; A(15,18)=-1;
A(16,13)=-2; A(16,17)=-2;

Mat1-14-real-apps
260
G.A. El-Sheikh MATLAB: Introductory Course 261

A(17,14)=-1; A(17,16)=-1; A(17,18)=-1; A(17,19)=-1;


A(18,15)=-1; A(18,17)=-1; A(18,20)=-1;
A(19,17)=-2; A(19,20)=-2;
A(20,18)=-1; A(20,19)=-1; A(20,21)=-1;
A(21,20)=-2;

% Define matrix for rhs


N = zeros(21,1);
N(1,1) = 200;
N(4,1) = 200;
N(7,1) = 200;
N(10,1)= 200;
N(13,1)= 200;

% SOlve for temps (compute inverse of A and move to other side).


AA = inv(A);
ANS = round(AA*N)

% Create matrix to mimic chimney


M = zeros(9,9);
M(6,4) = NaN;
M(7,3) = NaN; M(7,4)= NaN;
M(8,2) = NaN; M(8,3)= NaN; M(8,4)= NaN;
M(9,1) = NaN; M(9,2)= NaN; M(9,3)= NaN; M(9,4)= NaN;

M(5,5) = 200; M(6,5) = 200; M(7,5) = 200;


M(8,5) = 200; M(9,5) = 200; M(9,6) = ANS(1,1);

M(9,7) = ANS(2,1); M(9,8) = ANS(3,1);


M(8,6) = ANS(4,1); M(8,7) = ANS(5,1); M(8,8) = ANS(6,1);
M(7,6) = ANS(7,1); M(7,7) = ANS(8,1); M(7,8) = ANS(9,1);
M(6,6) = ANS(10,1); M(6,7) = ANS(11,1); M(6,8) = ANS(12,1);
M(5,6) = ANS(13,1); M(5,7) = ANS(14,1); M(5,8) = ANS(15,1);
M(4,6) = ANS(16,1); M(4,7) = ANS(17,1); M(4,8) = ANS(18,1);
M(3,7) = ANS(19,1); M(3,8) = ANS(20,1);
M(2,8) = ANS(21,1);

M(2,1) = M(9,8); M(2,2) = M(8,8); M(2,3) = M(7,8);


M(2,4) = M(6,8); M(2,5) = M(5,8); M(2,6) = M(4,8); M(2,7) = M(3,8);
M(3,1) = M(9,7); M(3,2) = M(8,7); M(3,3) = M(7,7);
M(3,4) = M(6,7); M(3,5) = M(5,7); M(3,6) = M(4,7);
M(4,1) = M(9,6); M(4,2) = M(8,6); M(4,3) = M(7,6);
M(4,4) = M(6,6); M(4,5) = M(5,6);
M(5,1) = M(9,5); M(5,2) = M(8,5); M(5,3) = M(7,5); M(5,4) = M(6,5);
M(6,1) = M(9,4); M(6,2) = M(8,4); M(6,3) = M(7,4);
M(7,1) = M(9,3); M(7,2) = M(8,3);
M(8,1) = M(9,2);
M(1,1) = M(9,9); M(1,2) = M(8,9); M(1,3) = M(7,9); M(1,4) = M(6,9);
M(1,5) = M(5,9); M(1,6) = M(6,9); M(1,7) = M(5,9); M(1,8) = M(2,9);

% Create 3-D color plot of solution


xx = 1:9;
yy = xx;
[x y] = meshgrid(xx,yy);
z = M;
mesh(z), grid on
title('Temperature in Chimney')
xlabel('width')
ylabel('depth')
zlabel('temp')

Fig. 14.5e: Temperature


Profile in Chimney

Mat1-14-real-apps
261
G.A. El-Sheikh MATLAB: Introductory Course 262

Mat1-14-real-apps
262
G.A. El-Sheikh MATLAB: Introductory Course 263

14.6 Example-14.6: Matrix Arithmetic


14.6.1 Matrix Addition
function c=add(a,b)

% c=add(a,b). This is the function which adds the matrices a and b.


% It duplicates the MATLAB function a+b.

[m,n] = size(a);
[k,l] = size(b);
if m~=k | n~=l,
r='ERROR using add: matrices are not of the same size';
return,
end
c = zeros(m,n);
for i=1:m,
for j=1:n,
c(i,j) = a(i,j)+b(i,j);
end
end

14.6.2 Matrix Multiplication


function c=mult(a,b)

% c=mult(a,b). This is the matrix product of the matrices a and b.


% It duplicates the MATLAB function c=a*b.

[m,n] = size(a);
[k,l] = size(b);
if n~=k,
c='ERROR using mult: matrices are not compatible for multiplication',
return,
end,
c = zeros(m,l);
for i=1:m,
for j=1:l,
for p=1:n,
c(i,j) = c(i,j) + a(i,p)*b(p,j);
end
end
end

For both of these programs you should notice the branch construction, which follows the size
statements. This is included as an error message. In the case of add, an error is made if we
attempt to add matrices of different sizes, and in the case of mult it is an error to multiply if the
matrix on the left does not have the same number of columns as the number of rows of the matrix
on the right. Had these messages not been included and the error was made, MATLAB would
have delivered another error message saying that the index exceeds the matrix dimensions. You
will notice in the error message the use of single quotes. The words surrounded by the quotes will
be treated as text and sent to the screen as the value of the variable c. Following the message is
the command return, which is the directive to send the control back to the function which called
add or return to the prompt. It is usually recommended to use the return command in the context
of an error message. Most MATLAB implementations have an error message function, either
errmsg or error, which you might prefer to use.

Mat1-14-real-apps
263
G.A. El-Sheikh MATLAB: Introductory Course 264

14.7 Example-14.7:
Use Bisection Method to Compute Zeros of a Function
Some more advanced features are illustrated by the following function. As noted earlier, some of
the input arguments of a function-such as tol in the example, may be made optional through use
of nargin (``number of input arguments''). The variable nargout can be similarly used. Note
that the fact that a relation is a number (1 when true; 0 when false) is used and that, when
while or if evaluates a relation, ``nonzero'' means ``true'' and 0 means ``false''. Finally, the
MATLAB function feval permits one to have as an input variable a string naming another
function.

function [b, steps] = bisect(fun, x, tol)


%BISECT Zero of a function of one variable via the bisection method.
% bisect(fun,x) returns a zero of the function. fun is a string
% containing the name of a real-valued function of a single
% real variable; ordinarily functions are defined in M-files.
% x is a starting guess. The value returned is near a point
% where fun changes sign. For example,
% bisect('sin',3) is pi. Note the quotes around sin.
%
% An optional third input argument sets a tolerence for the
% relative accuracy of the result. The default is eps.
% An optional second output argument gives a matrix containing a
% trace of the steps; the rows are of form [c f(c)].

% Initialization
if nargin < 3, tol = eps; end
trace = (nargout == 2);
if x ~= 0, dx = x/20; else, dx = 1/20; end
a = x - dx; fa = feval(fun,a);
b = x + dx; fb = feval(fun,b);

% Find change of sign.


while (fa > 0) == (fb > 0)
dx = 2.0*dx;
a = x - dx; fa = feval(fun,a);
if (fa > 0) ~= (fb > 0), break, end
b = x + dx; fb = feval(fun,b);
end
if trace, steps = [a fa; b fb]; end

% Main loop
while abs(b - a) > 2.0*tol*max(abs(b),1.0)
c = a + 0.5*(b - a); fc = feval(fun,c);
if trace, steps = [steps; [c fc]]; end
if (fb > 0) == (fc > 0)
b = c; fb = fc;
else
a = c; fa = fc;
end
end

Some of MATLAB's functions are built-in while others are distributed as M-files. The actual
listing of any M-file-MATLAB's or your own-can be viewed with the MATLAB command
type functionname. Try entering type eig, type vander, and type rank.

Mat1-14-real-apps
264
G.A. El-Sheikh MATLAB: Introductory Course 265

14.8 Example-14.8: Sorting


There are different types of sorting a data (numeric or characters) either in ascending or
descending orders. This section presents some of these algorithms with interactive programming
approach.

%*****************************************************
%*** sort04.m ***
%*****************************************************
%*** This program is a driver to test the sorting algorithm;
% *** 1- Bubble Sort Algorithm (Ascend) (sortbubble02.m)
% *** 2- Bubble Sort Algorithm (Descend) (sortbubble04.m)
%*****************************************************
clc
clear
close all
disp(' Bubble Sorting Algorithms ')
disp(' ================== ')
disp(' 1- Ascending ')
disp(' 2- Descending ')
disp(' 3- Both ')
flag1 = input(' Select one of the above: ');
% Entry of data to be Sorted
A = input(' Enter the vector to be sorted: ');
%*** Sorting
if flag1==1
A1 = sortbubble02(A); % run the bubble ascending sort
elseif flag1==2
A2 = sortbubble04(A); % run the bubble descending sort
elseif flag1==3
A1 = sortbubble02(A); % run the bubble ascending sort
A2 = sortbubble04(A); % run the bubble descending sort
end
%*** Displaying Sorted Data
disp(' Given Data; ')
disp(['[ ' num2str(A) ' ]' ])
disp(' Sorted Data; ')
if flag1==1
disp(['[ ' num2str(A1) ' ]' ])
elseif flag1==2
disp(['[ ' num2str(A2) ' ]' ])
elseif flag1==3
disp(['[ ' num2str(A1) ' ]' ])
disp(['[ ' num2str(A2) ' ]' ])
end

Mat1-14-real-apps
265
G.A. El-Sheikh MATLAB: Introductory Course 266

function A = sortbubble02(A)
%*****************************************************
% Bubble Sort Algorithm
% It is a simple sorting algorithm that repeatedly steps through the list
% to be sorted, compares each pair of adjacent items and swaps them if
% they are in the wrong order. The pass through the list is repeated until
% no swaps are needed, which indicates that the list is sorted.
% Example: we want to sort elements in the vector A
% >> A = [ 98 1 2 ........... ];
% >> SortedA = sortbubble02(A);
%*****************************************************
n1 = length(A);
if (n1 < 2)
disp(' ERROR; nothing to sort!! n1<2');
disp(' The number of coefficients should be > 2 ');
end
for i1 = 1:n1-1
for j1=1:n1-1
if (A(j1) > A(j1+1))
temp1 = A(j1);
A(j1) = A(j1+1);
A(j1+1) = temp1;
end
end
end

function A = sortbubble04(A)
%*****************************************************
% Bubble Sort Algorithm (descending order)
% It is a simple sorting algorithm that repeatedly steps through the list
% to be sorted, compares each pair of adjacent items and swaps them if
% they are in the wrong order. The pass through the list is repeated until
% no swaps are needed, which indicates that the list is sorted.
% Example: we want to sort elements in the vector A
% >> A = [ 98 1 2 ........... ];
% >> SortedA = sortbubble04(A);
%*****************************************************
n1 = length(A);
for i1 = 1:n1-1
for j1=1:n1-1
if (A(j1) < A(j1+1))
temp1 = A(j1);
A(j1) = A(j1+1);
A(j1+1) = temp1;
end
end
end

Sample Run:

Mat1-14-real-apps
266
G.A. El-Sheikh MATLAB: Introductory Course 267

Bubble Sorting Algorithms


==================
1- Ascending
2- Descending
3- Both
Select one of the above: 2
Enter the vector to be sorted: [-7 -60 56 34 12 0]
Given Data;
[ -7 -60 56 34 12 0 ]
Sorted Data;
[ 56 34 12 0 -7 -60 ]
>>

Sample Run:
Bubble Sorting Algorithms
==================
1- Ascending
2- Descending
3- Both
Select one of the above: 3
Enter the vector to be sorted: [12 0 56 -9 100 -60 4 7 66]
Given Data;
[ 12 0 56 -9 100 -60 4 7 66 ]
Sorted Data;
[ -60 -9 0 4 7 12 56 66 100 ]
[ 100 66 56 12 7 4 0 -9 -60 ]

Mat1-14-real-apps
267
G.A. El-Sheikh MATLAB: Introductory Course 267

15- MATLAB Lab Assignments


15.1 Variable, Operator and Expression
Q-1 Write a program to print HELLO WORLD on screen.
Q-2 Write a program to display the following output;
Subject Marks
Mathematics 90
Computer 77
Chemistry 69
Q-3 Write a program which accepts two numbers and prints their sum with difference in a
good format.
Q-4 Write a program which accept temperature in Fahrenheit and print it in centigrade.
Q-5 Write a program which accept principle, rate and time from user and print the simple
interest.
Q-6 Write a program which accepts a character and display its ASCII value.
Q-7 Write a program to swap the values of two variables.
Q-8 Write a program to calculate area of circle.
Q-9 Write a program to check whether the given number is positive or negative (using ?:
ternary operator)
Q-10 Write a program to check whether the given number is even or odd (using ? : ternary operator)
Q-11 Write a program to swap value of two variables without using third variable.
Q-12 Write a program which input three numbers and displays the largest number and its
index.
Q-13 Write a program which accepts days as integer and display total number of years,
months and days in it. For example: if user input is 856 days the output should be 2
years 4 months 6 days.
Q-14 Write a program that takes length as input in feet and inches, and then converts the
lengths into centimeters and displays it on screen. Assume that the given lengths in
feet and inches are,
a) integers
b) floating
Based on the problem, you need to design an algorithm as follows:
1. Get the length in feet and inches.
2. Convert the length into total inches.
3. Convert total inches into centimeters.
4. Output centimeters.
To calculate the equivalent length in centimeters, you need to multiply the total inches
by 2.54. Instead of using the value 2.54 directly in the program, you will declare this
value as a named constant. Similarly, to find the total inches, you need to multiply the
feet by 12 and add the inches. Instead of using 12 directly in the program, you will
also declare this value as a named constant; try to utilize a named constant that makes
it easier to modify the program later.

Mat1-15-assignments
267
G.A. El-Sheikh MATLAB: Introductory Course 268

15.2 Library Function


Q-1 Write a program which input principal, rate and time from user and calculate
compound interest. You can use library function; CI = P(1+R/100)T – P.
Q-2 Write a program to compute area of triangle. Sides are input by user;
Area = sqrt(s*(s-a)*(s-b)*(s-c)), where s=(a+b+c)/2.
Q-3 Write a program to check character entered is alphabet, digit or special character.
Q-4 Write a program which displays a number between 10 to 100, randomly.
Q-5 Write a program which accept a letter and display it in uppercase letter.
Q-6 Write a MATLAB program to implement the Number Guessing Game. In this game
the computer chooses a random number between 1 and 100, and the player tries to
guess the number in as few attempts as possible. Each time the player enters a guess,
the computer tells him whether the guess is too high, too low, or right. Once the player
guesses the number, the game is over.

Mat1-15-assignments
268
G.A. El-Sheikh MATLAB: Introductory Course 269

15.3 Single Dimension Array


Q-1 Write a MATLAB program to find the sum and average of one dimensional integer
array.
Q-2 Write a program to swap first and last element of an integer 1-d array.
Q-3 Write a program to reverse the element of an integer 1-D array.
Q-4 Write a program to find the largest and smallest element of an array.
Q-5 Write a menu driven program with following option;
a. Accept elements of an array
b. Display elements of an array
c. Sort the array using insertion sort method
d. Sort the array using selection sort method
e. Sort the array using bubble sort method
Write functions for all options. The functions should have two parameters name of the
array and number of elements in the array.
Q-6 Write a function to efficiently search for a data VAL from P, where P is one-
dimensional array of integers. If VAL is present in the array then the function should
return value 1 and 0 otherwise.
Q-7 Suppose a one-dimensional array AR containing integers is arranged in ascending
order. Write a user-defined function in MATLAB to search for an integer from AR
with the help of Binary search method, returning an integer 0 to show absence of the
number and integer 1 to show presence of the number in the array. Function should
have three parameters: (i) array AR (ii) the number to be searched and (iii) the number
of elements N in the array.
Q-8 Suppose A, B, C are arrays of integers of size M, N, and M + N respectively. The
numbers in array A appear in ascending order while the numbers in array B appear in
descending order. Write a user defined function in MATLAB to produce third array C
by merging arrays A and B in ascending order. Use A, B and C as arguments in the
function.
Q-9 Suppose X. Y, Z are arrays of integers of size M, N, and M + N respectively. The
numbers in array X and Y appear in descending order. Write a user-defined function
in MATLAB to produce third array Z by merging arrays X and Y in descending order.
Q-10 Given two arrays of integers A and B of sizes M and N respectively. Write a function
named MIX1 () with four arguments, which will produce a third array named C. such
that the following sequence is followed;
All even numbers of A from left to right are copied into C from left to right.
All odd numbers of A from left to right are copied into C from right to left.
All even numbers of B from left to right are copied into C from left to right.
All old numbers of B from left to right are copied into C from right to left.
A, B and C are passed as arguments to MIX1 (). e.g., A is {3, 2, 1, 7, 6, 3} and B is
{9, 3, 5, 6, 2, 8, 10} the resultant array C is {2, 6, 6, 2, 8, 10, 5, 3, 9, 3, 7, 1, 3}

Mat1-15-assignments
269
G.A. El-Sheikh MATLAB: Introductory Course 270

15.4 Two Dimension Array


Q-1 Write a menu driven program to do following operation on two dimensional array A
of size m x n. You should use user-defined functions which accept 2-D array A, and
its size m and n as arguments. The options are:
 To input elements into matrix of size m x n
 To display elements of matrix of size m x n
 Sum of all elements of matrix of size m x n
 To display row-wise sum of matrix of size m x n
 To display column-wise sum of matrix of size m x n
 To create transpose of matrix B of size n x m
Q-2 Write user defined functions for square matrix to calculate
 Left diagonal sum
 Right diagonal sum
Q-3 Write a user-defined function to display the multiplication of row element of two-
dimensional array A[4][6] containing integer.
Q-4 Write a user defined function named Upper-half() which takes a two dimensional
array A, with size N rows and N columns as argument and prints the upper half of the
array.
e.g.,
23150 23150
71531 1531
2 5 7 8 1 The output will be 1 7 8
01501 01
34915 5
Q-5 Write a function which accepts a 2D array of integers and its size as arguments and
displays the elements of middle row and the elements of middle column.
[Assuming the 2D Array to be a square matrix with odd dimension i.e. 3x3, 5x5, 7x7
etc...]
Example:
If the array contents is,
3 5 4
7 6 9
2 1 8
Output through the function should be:
Middle Row: 7 6 9
Middle column: 5 6 1
Q-6 Write a program to add two array A and B of size m x n.
Q-7 Write a program to multiply array A and B of order NxL and LxM

Mat1-15-assignments
270
G.A. El-Sheikh MATLAB: Introductory Course 271

15.5 General
Q-1- Write a MATLAB program to convert temperatures between the Fahrenheit and
9 5
Celsius scales, where; F  C  32 , C  (F  32)
5 9

Q-2- Design a program, using C++ programming, to find the roots (real and imaginary) of
 B  B2  4 A C
the quadratic equation; A x 2  B x  C  0 , X1, 2  .
2A
− Interacts with the user and reads these coefficients (A, B, C)
− Calculate the Roots (x1, x2) in all cases (real or imaginary)

Q-3- Displaying the results in a good format, design a MATLAB program to,
− Enter a set of measurements ended by a negative value
o Find the number of values (N)
o Find the maximum value (Vmax) and the minimum value (Vmin)
o Find the sum of these values (Vsum)
o Find the average value (Vav)
− Display the measurements in the following form;
No of Values Minimum Maximum Value Sum of values Average
Value Value

Q-4- Using MATLAB, write a program to manipulate strings;


 Interacts with the user to enter strings
 Finds the
‒ Length of string
‒ Number of words
‒ Reverse a String
‒ Concatenate Strings
 Display the results in a good format according to required action.

Q-5- Using MATLAB programming, design a program to be used with the exams-control for
finding students grades in your Institute such that it accepts the following inputs,
 Student name
 Course name
 Mark for each student and course
 Grade for each student and course
Then, it displays the list of students with courses and grades. In addition, it can show the
number of students in each grade with percentages or any other information. Consider the
given table to show you the grading system,
Score Grade
>=85 Excellent
75% - <85% V.Good
65% - <75% Good
50% - <65% Sufficient
<50% Fail
The output data has the form,

Mat1-15-assignments
271
G.A. El-Sheikh MATLAB: Introductory Course 272

No Student Name Course Name Mark Grade

Q-6- Using MATLAB, write a program to Manipulate Matrices;


 Asks the user to select the operation, and enter the matrices’ dimensions and
elements
 Reads the matrices’ dimensions and elements, Required action
 Finds the
‒ Sum of Matrix elements row-wise (display in column) , and
‒ Matrix Transpose
 Then displays the results in a good format.

Q-7- Displaying the results in a good format, design a MATLAB program to,
 Read a set of measurements and stops for -ve entry,
 find the sum and Average the measurements, and
 Display the results.

Q-8- Design only one MATLAB program to calculate and display the input and output data
in a good format;
(a) Circumference of a circle, C  2R , and
(b) Area of a circle, A  R 2
Q-9-a) Write a MATLAB program to calculate and display the Fibonacci sequence;
F(n )  F(n  1)  F(n  2)
-b) Write a MATLAB program to calculate and display the Factorial of a number;
N! (1) (2) ........ ( N  1) ( N)
-c) Write a MATLAB program to calculate and display the Sequence G1(n);
F(n ) F(n  1)  F(n  2)
G1(n )  
n! n!

Q-10- Using MATLAB, design a program to find the solution of the following algebraic
equations:
12 x 1  14 x 2  5 x 3  10 x 4  15
5 x 2  10 x 3  14 x 4  7
 7 x1  8 x 2  6 x 3  12
 5 x 1  15 x 2  16 x 4  20

Q-11- Design a MATLAB program to enter the following polynomials;


P1  18 s 5  25 s 4  14 s 2  32 s  35
P2  22 s 3  8 s 2  22 s  20
Then,
 Find the product (P1P2) using conv
 Find the sum (P1 + P2) using any of the flow-control commands
 Find the derivative of (P1)
 Find the roots of (P1)

Mat1-15-assignments
272
G.A. El-Sheikh MATLAB: Introductory Course 273

 Find the polynomial (P1) from its roots

Q-12-a) Using MATLAB, design a program to calculate and plot the function;
F1  sin( t )  e t
Where,
− =2f
− f = 2 Hz
− t = time history (0 to 3 [sec])
Plot the functions; sin, exponential and F1 with axes and legend for F1.

Q-13-b) Using MATLAB, design a program to;


− Generate a certain function (as you want) and save it in a data-file,
− Load the data/set of measurements,
− Plot this data with necessary labels,
− Find the maximum and minimum values,
− Find the average value, and
− Display the obtained information in a good format.

Mat1-15-assignments
273
G.A. El-Sheikh MATLAB: Introductory Course 274

16- Some of the General Purpose Commands


16.1 Commands

Mat1-16-commands
274
G.A. El-Sheikh MATLAB: Introductory Course 275

16.2 Operators and Special Characters

Mat1-16-commands
275
G.A. El-Sheikh MATLAB: Introductory Course 276

16.3 Logical Functions

16.4 Language Constructs and Debugging

Mat1-16-commands
276
G.A. El-Sheikh MATLAB: Introductory Course 277

16.5 Elementary Matrices and Matrix Manipulation

Mat1-16-commands
277
G.A. El-Sheikh MATLAB: Introductory Course 278

Mat1-16-commands
278
G.A. El-Sheikh MATLAB: Introductory Course 279

16.6 Specialized Matrices

16.7 Elementary Math Functions

Mat1-16-commands
279
G.A. El-Sheikh MATLAB: Introductory Course 280

16.8 Specialized Math Functions

16.9 Coordinate System Conversion

16.10 Matrix Functions - Numerical Linear Algebra

Mat1-16-commands
280
G.A. El-Sheikh MATLAB: Introductory Course 281

16.11 Data Analysis and Fourier Transform Functions

Mat1-16-commands
281
G.A. El-Sheikh MATLAB: Introductory Course 282

16.12 Polynomial and Interpolation Functions

Mat1-16-commands
282
G.A. El-Sheikh MATLAB: Introductory Course 283

16.13 Function Functions – Nonlinear Numerical Methods

16.14 Sparse Matrix Functions

Mat1-16-commands
283
G.A. El-Sheikh MATLAB: Introductory Course 284

16.15 Sound Processing Functions

Mat1-16-commands
284
G.A. El-Sheikh MATLAB: Introductory Course 285

16.16 Character String Functions

16.17 Low-Level File I/O Functions

Mat1-16-commands
285
G.A. El-Sheikh MATLAB: Introductory Course 286

16.18 Bitwise Functions

16.19 Structure Functions

16.20 Object Functions

Mat1-16-commands
286
G.A. El-Sheikh MATLAB: Introductory Course 287

16.21 Cell Array Functions

16.22 Multidimensional Array Functions

16.23 Plotting and Data Visualization

Mat1-16-commands
287
G.A. El-Sheikh MATLAB: Introductory Course 288

Mat1-16-commands
288
G.A. El-Sheikh MATLAB: Introductory Course 289

Mat1-16-commands
289
G.A. El-Sheikh MATLAB: Introductory Course 290

Mat1-16-commands
290
G.A. El-Sheikh MATLAB: Introductory Course 291

Mat1-16-commands
291
G.A. El-Sheikh MATLAB: Introductory Course 292

16.24 Graphical User Interface Creation

Mat1-16-commands
292
G.A. El-Sheikh MATLAB: Introductory Course 293

Mat1-16-commands
293
G.A. El-Sheikh MATLAB: Introductory Course 294

References
[1] Barrett, R., M. Berry, T. F. Chan, et. al., Templates for the Solution of Linear Systems:
Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994.
[2] Bequette, W, Process Control: Modeling, Design, and Simulation, Prentice Hall, 2003.
[3] Dingyu Xue, Y.Q. Chen, D.P. Atherton, Linear Feedback Control: Analysis and Design
with MATLAB, Springer-Verlag, 2002.
[4] Luyben, W.L., Process Modeling, Simulation and Control for Chemical Engineers, 2nd
Edition, McGraw-Hill, 1999.
[5] Gilbert, John R., Cleve Moler, and Robert Schreiber, Sparse Matrices in MATLAB:
Design and Implementation, SIAM J. Matrix Anal. Appl., Vol. 13, No. 1, January 1992,
pp. 333-356.
[6] Gupta, A.K., Numerical Methods using MATLAB, Springer Apress, 2014.
[7] Lindfield, G.R. and J.E.T. Penny, Numerical Methods using MATLAB, Third Edition,
Elsevier Inc. 2012.
[8] Lindfield, G.R. and J.E.T. Penny, Numerical Methods using MATLAB, Third Edition,
Elsevier Inc. 2019.
[9] Manassah, J.T., Elementary Mathematical and Computational Tools for Electrical and
Computer Engineers using MATLAB®, Second Edition, Taylor & Francis Group, 2007.
[10] Mathews, J.H. and K.D. Fink, Numerical Methods using MATLAB, 4th Edition, Pearson
Prentice Hall, 2004.
[11] Shampine, L. F., Numerical Solution of Ordinary Differential Equations, Chapman &
Hall Mathematics, 1994.
[12] Ram N. Patel, R.N. and A. Mittal, Programming in MATLAB: A Problem-Solving
Approach, Dorling Kindersley (India) Pvt. Ltd., 2014.
[13] The MathWorks documentation and Web site (www.mathworks.com) contains numerous
tutorials with M-files that have been written by users and MathWorks staff. These are
accessible by selecting Downloads. Also, Technical Notes, which is accessible from the
Technical Support Web site (www.mathworks.com/support), contains numerous
examples on graphics, mathematics, Simulink, and others.
[14]

Mat1-16-commands
294
G.A. El-Sheikh MATLAB: Introductory Course 295

Evaluation Sheet
for the Laboratory Assignments

Student: Academic
ID Name Department Year
2022/2023 - 01

Experiment Mark Instructor


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

Remark:
Any extra assignment and/or MATLAB experiment or simulation and
analysis should be recorded and evaluated in this table, as well.

Mat1-16-commands
295
G.A. El-Sheikh MATLAB: Introductory Course 296

The Author;
Dr. Gamal El-Sheikh has received his B.Sc. in Electrical Engineering from Military Technical
College (MTC), Cairo, Egypt, in 1980. He has worked as maintenance, tuning and
repair electrical engineer, Main workshop for guidance and control systems,
Egyptian Army, 1980-1985. Then he joined the MTC from 1985 until 2004. He
worked as Instructor and research assistant, Dept. of Guidance and Control at the
Military Technical College, Cairo, Egypt, 1985-1987. He worked as Part time M.Sc.
student, Full time teaching assistant at the Dept. of Guidance and Control at the
Military Technical College, Cairo, Egypt, 1987-1990. He has got his M.Sc. in
Electrical Engineering (guidance, control and navigation) from MTC, Cairo, Egypt,
in 1990. He has got his PhD degree in Electrical Engineering (robust self-tuning
control with aerospace applications) from the Industrial Control Centre, Strathclyde University, UK,
1994. He joined back the MTC as Lecturer and Chief for the Guidance and Control Engineering
Group, Dept. of Guidance and Control, MTC, Cairo, Egypt, 1994-2000. He awarded Associate
Professor in Electrical Engineering, and Chief of the Dept. of Guidance and Control, MTC, Cairo,
Egypt, 2000-2004. He worked as Full time professor in Electronics and Communications, Faculty of
Engineering, MSA University, 2004-2006. Full time professor, Head of the Computers and
Information Sciences Department, High Institute for Management, Banking, Computers and
Information Sciences, Sciences Valley Academy (SVA), 2006-2008. He worked as Visiting Professor
in College of Engineering, Karary University, Republic of Sudan, 2008-2009. Now he is a Visiting
Professor in MTC, Cairo, AIN Shams Universities. He has cooperative postgraduate-research
supervision with MTC, Cairo University aerospace Engineering, Alexandria University, Helwan
University, AIN Shams University. Supervisor of (40) PhD and MSc Thesis and (3) under-
supervision; Examiner: Internal (40) and External (20 MSc + 4 PhD); and author of more than (80)
papers published in local and international journals and conferences. His research interests include
control theories and design (Classical, Modern, Robust –LQG-GLQG-H- GH, Adaptive, Self-
Tuning Control, MRADC); Systems identification (linear and non-linear) with conventional and
intelligent techniques; Computers Control; Systems Simulation and Data Acquisition; Autopilot
design and analysis; Embedded systems with automation of industrial applications, PLC
(Programmable Logic Controllers) and microcontrollers (Atmell, PIC) with Arduino technologies;
Inertial Sensors (Gyroscopes and Accelerometers) in different technologies including: conventional,
laser, fiber-optic, solid state and MEMS, MEMS actuators, GPS; Guidance, Navigation and Control
with Autopilot design and embedded Flight Control. Telemedicine and Telepharmacy with
embedded and IoT systems with guidance and navigation in addition to remotely patient
monitoring.

Fields of interest:
 Telemedicine and Telepharmacy
 Automatic Control Theory and Design
 Advanced Control techniques (Modern Control, Robust Control, Adaptive Control, Self-tuning, Nonlinear
adaptive control, Neural Network Control, Fuzzy Logic Control).
 Computers Control and Interfacing
 Autopilot design and analysis
 Robotics with Guidance, Navigation and Control; including GPS and Processing/filtering
 Systems identification (linear and non-linear) with conventional and intelligent techniques (Neural network,
and Genetic programming and evolutionary algorithms)
 Embedded systems with automation of industrial applications using CNC (Computer Numerical Control),
PLC (Programmable Logic Controllers) and micro-controller (Atmell, PIC) with Arduino technologies.
 Systems Simulation (abstract and hardware in the loop)
 Satellites' communication and control
 Design and simulation of electronic and logic circuits using Matlab, Simulink and Modelsim (VHDL)
 Data Acquisition with different cards and peripherals
 Inertial Sensors (Gyroscopes and Accelerometers) in different technologies including: conventional, laser,
fiber optic, solid state and MEMS in addition to MEMS actuators and GPS
 Guidance and Control with Autopilot design and embedded Flight Control concerning missiles and
UAVs.

Mat1-16-commands
296

You might also like