Professional Documents
Culture Documents
Introductory Course
By
Cairo 2022
G.A. El-Sheikh MATLAB: Introductory Course i
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:
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 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.
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.
mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
iii
G.A. El-Sheikh MATLAB: Introductory Course iv
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
mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
v
G.A. El-Sheikh MATLAB: Introductory Course vi
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
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
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
mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
viii
G.A. El-Sheikh MATLAB: Introductory Course ix
References 294
mat1-00 Simulation Tools and CAD for Control Systems Design and Analysis
ix
G.A. El-Sheikh MATLAB: Introductory Course 1
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.
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
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
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
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. 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.
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.
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.
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.
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.
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
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.
To get the benefits of your time, you should record the outcome of the commands
and experiments in a notebook.
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.
mat1-01-int
9
G.A. El-Sheikh MATLAB: Introductory Course 10
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.
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].
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
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
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
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.
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
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.
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
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.
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
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
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
mat1-01-int
17
G.A. El-Sheikh MATLAB: Introductory Course 18
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.
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
mat1-01-int
19
G.A. El-Sheikh MATLAB: Introductory Course 20
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.
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.
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.
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
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.
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
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
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.
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.
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’.
mat1-01-int
27
G.A. El-Sheikh MATLAB: Introductory Course 28
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.)
mat1-02-vector
28
G.A. El-Sheikh MATLAB: Introductory Course 29
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.
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
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
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.
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);
>> 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
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
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
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 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.
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
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.
>> 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
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
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
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.
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.
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)
mat1-02-vector
38
G.A. El-Sheikh MATLAB: Introductory Course 39
^ 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.
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'
ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 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
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
>>
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.
>> 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
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
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.
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
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]
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
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
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.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.
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
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,
y = [1 0 0 0 1]
mat1-03-poly
48
G.A. El-Sheikh MATLAB: Introductory Course 49
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;
ans =
-5.5745
2.5836
-0.7951
0.7860
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.
mat1-03-poly
49
G.A. El-Sheikh MATLAB: Introductory Course 50
z=
17
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 ).
Polynomial Division:
Use deconvolution to divide back out of the product:
>> [q,r] = deconv(p12,p1)
q=
456
r=
00000
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
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.
mat1-03-poly
51
G.A. El-Sheikh MATLAB: Introductory Course 52
>> polyint(p,2)
ans =
0.2500 0 -1.0000 -5.0000 2.0000
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 )
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
mat1-03-poly
53
G.A. El-Sheikh MATLAB: Introductory Course 54
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.
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
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).
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.
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.
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.
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.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.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)
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!
mat1-05-files
62
G.A. El-Sheikh MATLAB: Introductory Course 63
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;
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
Example-5.4
A function may have multiple output arguments. For example:
function [mean, stdev] = stat(x)
[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.
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)
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;
mat1-05-files
66
G.A. El-Sheikh MATLAB: Introductory Course 67
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.
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
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)
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.
mat1-05-files
68
G.A. El-Sheikh MATLAB: Introductory Course 69
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.
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.
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.
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.
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
mat1-05-files
71
G.A. El-Sheikh MATLAB: Introductory Course 72
finish = i - 1;
token = string(start:finish);
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])
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);
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.
mat1-05-files
73
G.A. El-Sheikh MATLAB: Introductory Course 74
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.
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
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])
mat1-05-files
76
G.A. El-Sheikh MATLAB: Introductory Course 77
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)
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
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.
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))
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.
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.
if mod(n,2)==0,
b=1;
else b=0;
end
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’.
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
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.
mat1-06-flow-control
83
G.A. El-Sheikh MATLAB: Introductory Course 84
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
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.
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
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.
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.
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
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
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
%*********************************************************
%*** try01.m ***
%*********************************************************
clc
clear
close all
% 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
mat1-06-flow-control
90
G.A. El-Sheikh MATLAB: Introductory Course 91
if (strcmp(err.identifier,'MATLAB:catenate:dimensionMismatch'))
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)
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
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
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
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
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.
For example,
>> S1 = ['1 2' ; '3 4'];
>> str2num(S1) => [1 2;3 4]
ans =
1 2
3 4
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'];
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
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
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.
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
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]
mat1-07-string
100
G.A. El-Sheikh MATLAB: Introductory Course 101
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'};
ans =
1
0
0
>> strncmp(A,B,1)
ans =
1
1
0
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
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.
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
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
mat1-07-string
103
G.A. El-Sheikh MATLAB: Introductory Course 104
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
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.
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
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)')
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.
mat1-08-graphics
107
G.A. El-Sheikh MATLAB: Introductory Course 108
mat1-08-graphics
108
G.A. El-Sheikh MATLAB: Introductory Course 109
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)
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')
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. )
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
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
mat1-08-graphics
111
G.A. El-Sheikh MATLAB: Introductory Course 112
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
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!
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
>> 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')
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.
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
%************************************
%*** 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
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')
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.
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.
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;
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)
mat1-08-graphics
118
G.A. El-Sheikh MATLAB: Introductory Course 119
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
% a simple histogram
fig = figure;
hist(x)
%--PLOTLY--%
mat1-08-graphics
120
G.A. El-Sheikh MATLAB: Introductory Course 121
% 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--%
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
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');
for i=1:2
dat = get(xd(i),'XData');
dat = 2*dat/nbins - bound;
set(xd(i),'XData',dat);
end
%--PLOTLY--%
mat1-08-graphics
123
G.A. El-Sheikh MATLAB: Introductory Course 124
% horizontal histogram
sd = 0.1;
mu = 1;
data = mu + sd*randn(1,5000);
% bin specs.
nbins = 50;
%--PLOTLY--%
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
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
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
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.
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°.
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
Another example:
Mat1-08-graphics2
132
G.A. El-Sheikh MATLAB: Introductory Course 133
clc 180 0
clear
close all
0.4
%*** Creating a polygon using plot-command
n2 = 6; %*** 0.2
Mat1-08-graphics2
133
G.A. El-Sheikh MATLAB: Introductory Course 134
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
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
Alternatively;
%************************************
%*** polygon06.m ***
%************************************
%*** Demonstrates MATLAB commands ***
%*** to plot hexagonal grid representing a ***
%*** cellular network ***
%************************************
clc
clear
close all
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
Mat1-08-graphics2
138
G.A. El-Sheikh MATLAB: Introductory Course 139
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.
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
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
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')
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.
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.
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
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)
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).
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).
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
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.
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
Mat1-08-graphics2
148
G.A. El-Sheikh MATLAB: Introductory Course 149
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
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.
Mat1-08-graphics2
150
G.A. El-Sheikh MATLAB: Introductory Course 151
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
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
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.
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).
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.
t1 = 0:0.01:2*pi; -0.2
rclock1 = 1; % Clock Radius -0.4
lneedle1 = 0.95; % Needle length
-0.6
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.
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
-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
Mat1-08-graphics3
163
G.A. El-Sheikh MATLAB: Introductory Course 164
%************************************
%*** waveanimate01.m ***
%************************************ 1
Wave Animation
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.
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]
%*** Range
r1 = v1(1)*tf1; 5
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.
%************************************
%*** simulate02.m ***
%************************************
%*** Simulation: ***
%************************************
clc
clear
close all
Mat1-08-graphics3
167
G.A. El-Sheikh MATLAB: Introductory Course 168
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);
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;
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
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.
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.
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
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
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
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.
%************************************ 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
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
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
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
Mat1-08-graphics3
174
G.A. El-Sheikh MATLAB: Introductory Course 175
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.
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
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
%************************************
%*** 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);
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.
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.
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
%************************************
%*** 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];
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;
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
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
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
Height of Ball
e = 0.7;
n = 10;
5
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
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.
2s
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.
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
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;
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
0.7
N = 1000; 0.6
%generate the transmitted signal
0.5
x1 = rand(N,1)>0.5;
0.4
figure 0.3
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
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
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 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
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.
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
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
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
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
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)
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.
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
Therefore, the last day of a century can not be Tuesday or Thursday or Saturday.
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
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.
Mat1-09-dates
197
G.A. El-Sheikh MATLAB: Introductory Course 198
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:
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.)
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
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.
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}
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
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
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
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
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.
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)
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
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.
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
-2
-2.5
10.2 Solving one ODE 0 2 4 6 8 10 12 14 16 18 20
Mat1-10-ode
209
G.A. El-Sheikh MATLAB: Introductory Course 210
The empty brackets in the above statement are necessary and tell MATLAB to skip
the parameters t and x in the M-file conc.
%***************************************
%*** 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')
%************************************ 0.51
*** 0.508
0.506
dxdt1 = (c-x)/tau1;
0.504
0.5
0 5 10 15 20 25
Time [sec]
Mat1-10-ode
210
G.A. El-Sheikh MATLAB: Introductory Course 211
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:
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
%***************************************
%*** 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
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')
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];
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]
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
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.
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
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
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
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.
%************************************
%*** 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);
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
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
Example-10.7:
Evaluating the root of,
f(x)=sin(x)
Solution:
%************************************
%*** newtonraphson04.m ***
%************************************
clc
clear
close all
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)
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)
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:
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
Mat1-11-errors
225
G.A. El-Sheikh MATLAB: Introductory Course 226
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
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,
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
% 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
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])
Mat1-12-gui
229
G.A. El-Sheikh MATLAB: Introductory Course 230
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.
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
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)
*Enable
set(handles. tb1, 'Enable', 'off');
set(handles. tb1, 'Enable', 'on');
Example:
In the previously shown GUI the code added to the m file under the plot button call back
function as follows:
% 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;;
Mat1-12-gui
232
G.A. El-Sheikh MATLAB: Introductory Course 232
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.
Array operations:
Mat1-13-sessions
232
G.A. El-Sheikh MATLAB: Introductory Course 233
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
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.
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 = 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.
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.
>> [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.
Mat1-13-sessions
236
G.A. El-Sheikh MATLAB: Introductory Course 237
Plotting:
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,'y-',X,Y,'go') Plots the data twice, with a solid yellow line
interpolating green circles at the data points.
Mat1-13-sessions
237
G.A. El-Sheikh MATLAB: Introductory Course 238
Example: A helix
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.
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.
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.
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
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)).
Mat1-13-sessions
240
G.A. El-Sheikh MATLAB: Introductory Course 241
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".
i = 1; 800
i = i + 1; 500
end 400
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)
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
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
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]
Mat1-14-real-apps
243
G.A. El-Sheikh MATLAB: Introductory Course 244
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
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(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.
Mat1-14-real-apps
247
G.A. El-Sheikh MATLAB: Introductory Course 248
xm = mean(ex3data(:,2));
xd = std(ex3data(:,2));
hold;
plot (data(:,1), data(:,2), 'b');
plot (data(:,1), data(:,3), 'b:');
plot (data(:,1), data(:,4), 'b:');
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
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.
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:
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
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
Mat1-14-real-apps
250
G.A. El-Sheikh MATLAB: Introductory Course 251
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));
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
[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
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
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.
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
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
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
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;
for i = 2:4
for j = 1: 11-i
T(i,j) = T(10-j,10-i);
end
end
Mat1-14-real-apps
257
G.A. El-Sheikh MATLAB: Introductory Course 258
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;
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,
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
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.
Mat1-14-real-apps
260
G.A. El-Sheikh MATLAB: Introductory Course 261
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
[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
[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.
% 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);
% 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
%*****************************************************
%*** 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
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
Mat1-15-assignments
267
G.A. El-Sheikh MATLAB: Introductory Course 268
Mat1-15-assignments
268
G.A. El-Sheikh MATLAB: Introductory Course 269
Mat1-15-assignments
269
G.A. El-Sheikh MATLAB: Introductory Course 270
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-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
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 2R , 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
Mat1-15-assignments
272
G.A. El-Sheikh MATLAB: Introductory Course 273
Q-12-a) Using MATLAB, design a program to calculate and plot the function;
F1 sin( t ) e t
Where,
− =2f
− f = 2 Hz
− t = time history (0 to 3 [sec])
Plot the functions; sin, exponential and F1 with axes and legend for F1.
Mat1-15-assignments
273
G.A. El-Sheikh MATLAB: Introductory Course 274
Mat1-16-commands
274
G.A. El-Sheikh MATLAB: Introductory Course 275
Mat1-16-commands
275
G.A. El-Sheikh MATLAB: Introductory Course 276
Mat1-16-commands
276
G.A. El-Sheikh MATLAB: Introductory Course 277
Mat1-16-commands
277
G.A. El-Sheikh MATLAB: Introductory Course 278
Mat1-16-commands
278
G.A. El-Sheikh MATLAB: Introductory Course 279
Mat1-16-commands
279
G.A. El-Sheikh MATLAB: Introductory Course 280
Mat1-16-commands
280
G.A. El-Sheikh MATLAB: Introductory Course 281
Mat1-16-commands
281
G.A. El-Sheikh MATLAB: Introductory Course 282
Mat1-16-commands
282
G.A. El-Sheikh MATLAB: Introductory Course 283
Mat1-16-commands
283
G.A. El-Sheikh MATLAB: Introductory Course 284
Mat1-16-commands
284
G.A. El-Sheikh MATLAB: Introductory Course 285
Mat1-16-commands
285
G.A. El-Sheikh MATLAB: Introductory Course 286
Mat1-16-commands
286
G.A. El-Sheikh MATLAB: Introductory Course 287
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
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
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