0 ratings0% found this document useful (0 votes) 67 views74 pagesIntroduction To Matlab-UoL
An introduction to Matlab for beginners
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Contents
PrefACe..eesessseeee
Contents... ui
1. Intoduetion.....
1.1 Definitions...
1.2 Types of Programming Languages.....
1.3 Programming for Problem-solving .....
1.3.1 Problem Analysis...
1.3.2 Algorithm Design
1.3.3 Program Coding...
1.3.4 Execution.
1.3.5 Maintenance..
2. Problem Analysis and Algorithm Design.......
2.1 Sequential Control...
ee
2.1.1 Examples ..
2.1.2 Exercises.
2.2 Selection Control.....
2.2.1 Examples ..
2.2.2 Exercises...
2.3 Repetition Control...
2.3.1 Repetition controlled by a counter...
2.3.2 Repetition controlled by a logical expression.
2
Examples
2.3.4 Exercises.
3. Problem Coding Using MATLAB...
3.1 Introduction to MATLAB ..vsccrceo
3.1.1 Statements and Variables......cccc
3.1.2 Matrices...
3.1.3 Graphics
3.1.4 Scripts
3.1.5 Input/Output Statements and Reading/Writing Data Files...3.1.6 Examples...
3.1.7 Getting Help and Further Information. 49
3.2 Programming using MATLAB
3.2.1 Sequential Control in MATLAB...
3.2.2 Selection Control in MATLAB...
3.2.3 Repetition Control in MATLAB 53
3.2.4 Examples.......
3.3 Exercises...
4. More on Programming Using MATLAB. o7
5. Application to Commonly-encountered Programming Problems. 68
6, Application to Problems in Science and Engineering,
7. Miscellaneous Topics in Programming Using MATLAB...
Answers to Some Selected Problems. 11. Introduction
1.1 Definitions
The definitions of some common terms that are used when describing and classifying
programming languages are given as follows:
Programming Language: A set of prescribed formal language (that is, syntax, or grammatical
rules) for instructing a machine (for example, a computer) to perform specific tasks or step-
by-step calculations.
Machine Code: Instructions executed directly by the central processing unit (CPU) of a
computer.
Source Code: Instructions written in human-readable format and are first transformed into
machine code by a compiler (also called interpreter) in order to be executed by the
computer's CPU.
1.2 Types of Programming Languages
1. Classification based on the level of abstraction:
By abstraction, we mean ‘hiding details” of how it works.
Low-level programming language: A programming language with little or no abstraction
from the instruction set of the computer. An example of this is the x86 machine code or
assembly language; you may readily see the 0’s and 1’s or the hexadecimal notations in the
code.
High-level programming language: A programming language with a high level of abstraction
from the instruction set of the computer. Examples of this are FORTRAN and C. Thus, high-
level programming languages are also source codes,
Note: ‘High’ or ‘Low’ are relative terms; a programming language that may be high 30 years
ago can be considered a low one today. Therefore, the amount of abstraction, in some sense,
should define how high or low a programming language is. In general,
High-level = Easy to read by man
Low-level = Difficult to read by man
2. Classification based on how it executes instructions:
Compiled programming language: To execute instructions, it first converts all the source
code to a machine code; this process is often called ‘compiling’. Examples of compiled
programming languages are C, C++, FORTRAN, Java, and AdaInterpreted programming language: To execute instructions, it converts the source code to a
machine code one step at a time (that is, step-by-step). Examples of interpreted programming
languages are BASIC, MATLAB, and Python. Technically, there is a step-by-step
compilation involved; that is, every line of code, for instance, is compiled independently (that
is, not altogether and at once as with the compiled programming language case).
Note: A compiler, or an interpreter, is also a computer program: its input is a source code and
its output is a machine code. Table 1.1 summarizes the features of a compiled programming
language and an interpreted programming language for comparison.
Table 1.1: A comparison of the compiled and the interpreted programming languages
Compiled programming language
Interpreted programming language
1, To use it, you have to compile the
entire program source code
2. Enror is displayed after the entire
It involves a step-by-step compilation;
each line, section or block is compiled
ata time.
Error is displayed after every line,
program is checked. section, or block is checked
They are generally much slower than
the compiled programming
counterpart.
3. In general, they are very fast
programming languages (mainly
because they execute some control
statements very fast),
As an illustration, the source code to solve the following simple mathematical problem using
two different programming languages (C — a compiled programming language, and
MATLAB ~ an interpreted programming language) is given in Table 1.2:
Given that z= x+y, find z if x = 3 andy = 4.
Table 1.2: A program to solve a simple mathematical problem using C and MATLAB
‘Compiled programming language Taterpreted programming language
«© (MATLAB)
#include =3ry
main() zpexty
4
float 3.0, y = 5.0, 23
THEN, press the ENTER key
zeetyPrint ($E\n",2)7
urn 0;
click compile
1.3 Programming for Problem-solving
Problem solving is usually the primary goal in science and engineering for learning how to
program with a computer. It requires a great deal of imagination, inventiveness and ingenuity.
In general, the stages involved in using a computer program to solve a problem may be
outlined as follows:
1. Problem analysis
. Algorithm design
. Program coding
4. Execution
Maintenance
1.3.1 Problem Analysis
Problem analysis involves understanding the problem, its requirements and its specification.
Important elements of problem analysis include the following:
a. Understanding and analysing the problem: This involves identi
problem and the information available to solve the problem.
ig the key message of the
b. Specification: This involves the description of the inputs and outputs
©. Generalization: This involves thinking broadly; that is, identifying solution that will not
only solve the problem but could also solve similar problems with little or no modification.
d. Divide and conquer: This involves breaking down the problem into smaller and
manageable parts. This technique is particularly useful in solving very complex problems,
1.3.2 Algorithm Design
Algorithm design involves the development of a step-by-step procedure that will use the
given input to calculate and produce the required output. The designed algorithm can be in
any of the following formsa. Pseudocode
b. Graphical representation (e.g., flowcharts, structure diagrams, ete.)
Notes:
() A pseudocode is an English-like writing that explains in a step-by-step manner what
needs to be done with the known information in order to obtain the required solution to a
given problem. There are no specific rules in writing a pseudocode and it is different for
every programmer.
(ii) Flowcharts are examples of graphical representation of an algorithm and are used with,
or to replace pseudocode. They are not the only graphical representation available, however.
(iii) Symbols used in algorithm design using flowcharts are given in Table 1.3.
Table 1.3: Symbols used in algorithm design using floweharts
Symbol ‘Name Funetion
Anoval Indicates a beginning or an end of an
algorithm
A parallelogram Indicates the input or the output information
Arectangle Indicates the assignment of values to variables
(eg.x=5.y=54+3,2= VbF Far, ete)
A diamond shape Indicates a selection
‘An open-ended rectangle | Used for making comments
He UO0
An hexagon Indicates the beginning of a repetition
structure (a repetition is also called a loop or
an iteration)
A double-lined rectangle | Indicates a reference to a sub-algorithm (e.g. 2
subroutine or a function)
LO
‘An arrow; an arrow and | Arrows indicates flow lines
fa circle: and, arrows | Circles are often used when the use of
with a citele continuous lines are inconvenient or where
flow lines join,
<_
ToeOff-page connectors _| The first of these is used for terminating a flow
line on one page and the second for resuming
the flow line on another page
(iv) Algorithms to solve any problem (no matter how difficult) involves only three basic
methods of control; these are as follows
a. Sequential (that is, [])
b Selection (that is, <>)
c. Repetition (that is, (7)
1.3.3 Program Coding
The writing of a computer program in a programming language to implement a step-by-step
procedure or a designed algorithm is ealled coding. Usually, you will also include some form
of documentation in the code to help you in remembering (or for other people to understand)
what some lines of the code are meant to do. Properties of a “good code’ include:
a. It should be structured; that is, it should be clear. Clarity could be improved by the correct
use of subroutines (or, functions ~ these are codes that perform specific task), block structures
(a block structure is a section of a code that is grouped together) and control structures
(sequential, selection, and repetition controls)
b. It should be well documented (with comment lines).
¢. It should be formatted in a style that improves readability.
1.3.4 Execution
The execution of a program involves checking, testing, debugging, and formatting your
results, Your program must produce the correct results of the solution to the problem given in
the specification. The process of checking that it does is known as the program validation
process,
Also, errors may occur in your program development process. The process of checking that
the program is free from errors and complete is known as the verification process.Itis important to run the program many times during the checking process; it would be usefull
to also do this with input data for which the correct results are known in advance. This
process is known as the testing process.
Furthermore, errors are frequent and common when designing a program or during a
program’s execution. It is part of a programmer's respousibility to figure out or detect these
errors as they may prevent program execution, terminate the program or enable the program
to give incorrect results. There are three types of errors that may occur during the process of
program design and execution; these are as follows:
a. The syntax errors (also called compiled-time errors): Examples of the causes of syntax
errors are incorrect punctuation, unbalanced parenthesis, and misspelled keywords. A syntax
error is detected during the compilation of the program (or when the program is being
interpreted, as the case may be) and a programming language gives an error message. The
programming language and/or its manual can give an indication on the cause of the error.
b. The run-time errors: Examples of the causes of these errors are a division by zero or an
integer overflow. A run-time error is detected during the program execution (it may not be
detected during compilationinterpretation) and the operating system reports an error
message. The manual of the operating system’s manufacturer can provide the meaning of this
error message
¢. The logic errors: Examples of the causes of these errors are incorrect implementation of
algorithm and designing an incorrect algorithm for the problem. Logic errors are usually
more difficult to identify and correct since there are no error messages displayed to assist
programmers. (Because there are error messages involved, the syntax and run-time errors are
easier to detect). There are, however, few techniques that may assist in detecting logic errors
but they do not work in every case. These techniques include:
i. Dividing the program into segments and ensuring each segment works properly.
ii, Testing the program with inputs whose outputs are known in advance; also test
each segment in this manner.
iii, Tracing the change in the values of the variables in loops when selection and/or
repetition controls are implemented.
1.3.5 Maintenance
Problem analysis, algorithm design, program coding and execution, together, although may
look simple, can be used to solve even the most difficult and complex problems in science
and engineering. Thus, student-grade programming problems stop with these stages. In real
world programming projects, maintenance of the programs are often required in order to fix
some flaws that were only identified after long use, to improve the performance of the
6program, to add new features to the program, and/or to enable the program to be implemented
on another computer operating system or hardware, among other reasons. In most cases, it is
easier to carry-out maintenance activities on a “good code’; therefore, it is important to leam
to write good codes.2. Problem Analysis and Algorithm Design
2.1 Sequential Control
Sequential control refers to the execution of a program in sequence. The structure of a
sequential control is shown in Figure 2.1
Figure 2.1: Structure of a sequential control
Note!
a. It cannot perform selection — hence, the need for selection control
b. It can be repeatedly used to carry out calculations where the values of the parameter
changes. It is advantageous, however, to use repetitive control to cary out the same
calculation many times with different (often incremental change in) parameter values (that is,
instead of repeating the same thing over and over, let the computer do it!). The use of
repetitive control becomes handy when it will be too long or impossible (rime-wise and
Nyping-space-wise) to carry out repetitive calculations using sequential control (for example,
in finding the sum of all prime numbers between 1 and 100,000,000).
2.1.1 Examples1. The approximate speed (in metre per second) of a satellite moving in a circular orbit about
a celestial body can be expressed as follows:
k
a
where k is a constant (in metre cubed per second squared) which depends on the celestial
body and d is the distance (in metre) between the satellite and the centre of the celestial body.
Using a flowchart, design an algorithm that reads the values of k and d from a user’s input
and calculates and displays the corresponding speed of the satellite.
speed
2. The equation of the curve formed by a handing cable of weight w in kilogram per metre of
length can be described by the following expression
ysa cosh)where =4 , h is the horizontal tension of the cable at its low point, and cosh is the
hyperbolic cosine function. Using a flowchart, design an algorithm that reads values of w, h,
and x and then calculates and prints the corresponding value of y (of course, x and y are the
horizontal and vertical coordinate values, respectively).
We ey loge deel bar = lon fice,
Ce a pent
whee 2
a
“te fora ha aban Bx sll
3. The period p of a simple pendulum can be obtained using the following formula:
par Es tane(2)
N
where g = 980 cm/sec”, lis the length of the simple pendulum (cm), and @ is the angle of
displacement (degrees). Using a flowehart, design an algorithm that reads the values of ! and
6 and then calculates and displays the corresponding value of the period of the simple
pendulum.
19Seanad
Mie nebo Ss
pea: peel. (i +e &¢))
cepts
Get P
Polo cde
fle fa vals YL 6 Le
Gupte Poot
fe monte
[Pon
LP
Diplay Hevols 4 P
e
2.1.2 Exercises
1. The acceleration a of a car that is subject to aerodynamic resistance which is proportional
to the square of its velocity v and constant frictional resistance can be written as follows:
a= -ky- kyu?
where ky and kz are constants that depend on the mechanical configuration of the car. If the
car has an initial velocity vp when the engine is disengaged, the distance d for which it will
coast to stop can be written as follows:
Fen +Eet)
where In( ) denotes the natural logarithm. Using a flowchart, design an algorithm that reads
the values of k, , k . and vp and then calculates and displays the value of a at the instant the
engine was disengaged and the value of d.
ul2. The x- and y-components of the velocity and displacement of a projectile ejected into an
experimental fluid (as shown in Figure Ex 2) for time t 2 0 can respectively be expressed as.
follows:
Velocities Ue = (V9 cos Be
(vosind +2) em 2
Displacements: xs ee
key
vy sind +2) (1—
where vp is the initial speed of the projectile and @ is the angle to the horizontal. Using a
flowchart, design an algorithm that reads the values of vo, @, k and ¢ and then calculates and
displays vy, vy, x and y.
See. 2.1.2 / Figure Ex 2
3. The values of d and @ (as defined in Figure Ex 3) for a particle P that starts at rest at point
O and time t = 0 and undergoes a constant tangential acceleration @ as it passes through the
circular slot a time t > 0 in the counter-clockwise direction can be obtained using the
following equations:
d
Using a flowchart, design an algorithm that reads the values of r, a, and t and then calculates
and displays 6 and d.See. 2.1.2 / Figure Ex 3
4, The expressions for the components of the velocity in the spherical coordinates (R, 0, 9)
of an aircraft flying in a horizontal circle of radius d with a constant speed w at an altitude A
from a radar tracking unit located at C are as follows
vp = isin
= tus
0 feaesie ne
vg =usin(2)
~nucoe(®)
Frenne Q)vn
where a is the angle that defines the position of the aircraft in the horizontal circular plane as
it revolves. Using a flowchart, design an algorithm that reads the values of a, d, h, and u and
then computes Up . Vp . Up
=
pay a
—
SS
\
&
Sec. 2.1.2 / Figure Ex 4
B5. A simple pendulum pivoted at O is fiee to swing in a cart as shown in Figure Ex 5. If the
cart, which moves on an inclined plane of inclination angle @ is given a constant acceleration
a, the steady angle oc assumed by the pendulum (neglecting the mass of the support rod) after
the transient has died down can be expressed as follows:
c= tan (#20882),
where g = 9.8 nvsec”, Using a flowchart, design an algorithm that reads the values of a and
6 and calculates and displays ec
See. 2.1.2 / Figure Ex 5
2.2 Selection Control
Selection control refers to the execution of a program involving the selection of one of
several alternative set of statements (this can be accomplished using the ‘i statement in
MATLAB, FORTRAN, Java or BASIC, for instance). The selection is based on the value of
a logical expression. In general, logical expressions are those whose results are Boolean
values (that is, True or False, 0 or 1, etc.) when evaluated, In many cases, logical expressions
can be constructed using the relational and logical operators in Table 2.1. The structure of a
simple selection control is shown in Figure 2.1. Figure 2.2 shows a more general selection
control structure
Table 2.1: Relational operators and logical operators
Relation Description Logical Description
Operator Operator
< Less than not | Negation
> Greater than and Both at the same time
(sinmitaneonsly)
= Is equal to
or __| Either
4= Ts less than or equal to
Is greater than or equal to
ie Is not equal to
Figure 2.1: Structure of a simple selection control
Tm ple
a
cn} “ae
Figure 2.2: A general structure of a selection controlNote:
a, It is possible that the ‘sequence of statements’ in the general structure of Figure 2.2
contains one or more other selection controls; in this case, it is called a compound selection
control structure. An example structure of a compound selection control is shown in Figure
23.
Figure 2.3: An example of a compound selection control
b. It is also possible for the logical expression to have many alternatives (not just two: True or
False); in this case, the general structure is called a multi-alternative selection structure. An
example structure of a multi-alternative selection control is shown in Figure 2.4. It should be
noted that it is always possible to decompose a multi-alternative selection control into a series
of simple selection controls as illustrated in the pseudocode of Table 2.2 (but the original
selection control and the decomposed selection control are, however, not exactly equivalent)
16Figure 2.
Table 2.2: Pseudocode illustrating the decomposition of an example multi-altemative
selection control into a series
: Au example of a multi-altemative selection control
of simple selection controls
A multi-alternative selection control
A series of simple selection controls
zex-y
alse if x>y (and) x <
else if x>y (and) x< 8
zyx
end
ifx>y(and)x <5
zex?
end
ifx>y(and)x<8
zy?
end
2.2.1 Examples
1. The safe loading of column 1 (in kilo-Newton per square metre) with slimness ration s can
be computed using the following formula:
113800 - 2275s? if s < 260
E mes) ifs 2260
aUsing a flowchart, design an algorithm that reads the value of s and then calculates and
displays the value of L.
2. The roots of a quadratic equation ax? + bx +c = 0 can be obtained using the quadratic
formula as follows:
—b + Vb? — 4ac
zi
2a
Using a flowchart, design an algorithm that reads the values of a, b and c and calculates the
roots of the corresponding quadratic equation and states whether the roots are any of the
following:
(a) real and distinet,
(b) real and double, or
(©) complex roots.
1s2.2.2 Exercises
1. Using a flowchart, design an algorithm that reads two numbers x and y and determines and
displays which is larger.
2. The equation of a cirele with the origin as its centre (0, 0) and with radius r is given as
follows:
reaxe ty?
where x and y are the coordinates in the Cartesian system. Using a flowchart, design an
algorithm that reads any point (p, q) and determines whether the point lies within the cirele.
(Hint: A point lies within the circle if > /p? + q?)
3. Using a flowchart, design an algorithm that reads an integer n and determines if itis even
or odd.
2.3 Repetition Control
9Repetition control refers to the execution of a program involving the repetition of one or
more statements. There are two types of repetition control, namely:
a, Repetition controlled by a counter
». Repetition controlled by a logical expression
2.3.1 Repetition controlled by a counter
In repetition controlled by a counter, the loop is executed for each value of some control
variable with a pre-specified range of values; this can be accomplished by the ‘do’ statement
in FORTRAN and the ‘for’ statement in MATLAB, C, C++, Java, BASIC, and Ada, for
instance. The counter controlled loop is also called the for-loop. The structures of a simple
and a general counter controlled repetition are shown in Figure 2.5 and Figure 2.6,
respectively. It should be noted that the counter controlled repetition requires the knowledge
of an initial value, an end value and an incremental value (step size) of the control variable.
est
9 eb venchla ict
5 oR
Figure 2.5: Structure of a simple counter controlled repetition loopFigure 2.6: Structure of a general counter controlled repetition loop
2.3.2 Repetition controlled by a logical expression
In repetition controlled by a logical expression, the loop continuity or termination is
determined by the value of some logical expression. It can be accomplished using the
‘while’ statement in MATLAB, Java, C, C++, and the “do while” statement in FORTRAN.
The logical expression controlled loop is also called the while-loop. Recall that the counter
controlled repetition requires the knowledge of an initial value, an end value and an
incremental value. The knowledge these means that the number of repetitions (iterations) is
known in advance. There are many important and practical problems where the number of
iterations is not known in advance and/or it is impossible to determine it in advance. In such
problems, the logical expression controlled repetition can be used. Moreover, the logical
expression controlled repetition can also be used to implement the counter controlled
repetition ~ making the logical expression controlled repetition the more general of the two
repetition control structures. Two examples (the pre-test and the post-test) of simple logical
expression controlled repetition structures are shown in Figure 2.7 and the general structure is
shown in Figure 2.8,te 1 (em) (ost e
(a) The pre-test structure (b) The post-test structure
Figure 2.7: Examples of simple logical expression controlled repetition structures
Figure 2.8: The general structure of a logical expression controlled repetition
2.3.3 Examples
Examples on counter controlled repetition structure
1. Using a flowchart, design an algorithm that reads an integer NV and then prints out the
numbers 1 to N and their squares.2. Using a flowchart, design an algorithm that reads an integer NV and prints out the even
numbers between 1 and N but does not print out numbers between 50 and 60 inclusive.3. Using a flowchart, design an algorithm that reads the value of x and evaluates the
following infinite series:
sinx
using the first 10 terms and prints out the approximate values of sinx as each term in the
series is added, Note that n! =n x (n — 1) x (n— 2) X32 1.4, Using a flowchart, design an algorithm that calculates the values of y for values of ¢ from
0 to 5 in increments of 0.01 and displays the value of y in each iteration. The expression for
y is defined as follows
y = cost +0.5sint
Shier eon
=
MT? 8
Cob thee =F
Examples on logical expression controlled repetition structur
5. Using a flowchart, design an algorithm that reads the value of k and finds the smallest
positive integer NV such that the sum
1t24+34+—N
is greater than the value of k. Your algorithm should also display the value of the sum.6. Using a flowchart, design an algorithm that reads the value of x and evaluates the
following infinite series:
Your algorithm should find and display the approximate value of sin by summing the first
17 terms of the series such that the addition or subtraction of the (1 + 1)" term to the series
adds a negligible amount that is less than 10-7 to the approximate value. Your algorithm
should also display the number of terms that was used in the approximation.2.3.4 Exercises
1. Using a flowehart, design an algorithm that reads two integers x and y and calculates the
sum of all the integers between them.
2. For each of the following functions of y, design an algorithm using a flowchart that
calculates the values of y for values of t from 0 to 10 in increments 0.01 and displays the
value of y for each iteration:
(a) y = 2cost +3sint
(b)y=
() y = 3cos4t —sin4t
(d) y =e *(2cost + 3sint)
(ey =e t+ Ge-Itet(® y = 3cos(5) - 4sin()
(2 cost — e* sin 3t
@y=
3. A ship with a total displacement of d starts from rest in still water with a constant propeller
thrust of u. The total resistance r to the motion of the ship as it travels on the water can be
assumed to be as follows:
45v?
where v is the ship’s velocity which can be obtained using the following equation:
7
a5 ¢
and s is the distance travelled by the ship. The ships acceleration a can also be expressed as
follows
Using a flowchart, design an algorithm that reads the values of d, u and s and then displays
the values of v and a as the ship travels from the distance of 0 to s in increments of 0.2.
4. A long thin metallic bar is to be carried horizontally in a passage consisting of two
hallways, one of 8 m width and the other of 13 m width, The two hallways meet at a right
angle and the top view of the passage and the bar is shown in Figure Ex 4. The bar is to be
carried from the narrower hallway to the wider one, From the figure (using similar triangles),
it can be shown that
Using a flowchart, design an algorithm that initializes at x = 8.1 and increments x by 0.1 to
find, to the nearest 0.1 m, the length of the longest bar that can be carried along the passage.
(Bint: The length of the longest bar is the same as the minimum value of 1)See. 2.3.4 / Figure Ex 4
5. A 60 kg load is to be hanged from the end of a straight bar so that the bar is horizontal and
attached to a building by a pin joint using a cable as shown in Figure Ex 5. The bar and cable
are each of 8 m in length and the tension T in the cable can be expressed as:
3840
x V6E= x7
where x is the distance between the point the cable is attached to the bar and the wall. Using a
flowchart, design an algorithm to find x such that the tension in the cable is minimum. (Hint:
‘You may start with x = 1 and increment x by 0.1 to compute various values of T. The value
of x, to the approximate 0.1 m, for which the value of 7 is minimum is the required solution)
See. 2.3.4 / Figure Ex 53. Problem Coding Using MATLAB
3.1 Introduction to MATLAB
In solving a problem using a computer, algorithms must be translated (coded) into writings
that strictly adhere to the syntaxes (grammatical rules) of the programming language that we
want to use. MATLAB is an interpreted and a high-level programming language that is
highly interactive, making it suitable for scientific and engineering computations. The name
MATLAB stands for MATrix LABoratory and it reflects the original intention for
MATLAB’s development — which was to provide easy access to two FORTRAN packages
for linear algebra and numerical computations namely, LINPACK (linear system package)
and EISPACK (eigen system package), without having to learn FORTRAN.
The implementation of an algorithm with a computer (or coding) means processing input data
with the computer in order to produce the required result. Therefore, a programming
language must not only be able to accept and store (save) data but nmust also be able to
process the data by carrying out operations on the data in a step-by-step manner as described
in the code. The fundamental data type in MATLAB is a matrix; that is, any input data type is
considered a matrix (accordingly, a vector is treated as a I-dimensional matrix and a scalar is
a vector with one element)
To start MATLAB on a PC with Windows operating system that has MATLAB installed on
it, click on the ‘Start’ button from the Windows desktop and navigate through to ‘All
Programs’ and then click on MATLAB. The MATLAB desktop similar to that in Figure 1.1
appears. It contains the following panels:
(a) Current Folder: This area displays the contents of the current folder you are working
in, It also gives you access to files you have stored in the folder.
(b) Command Window: This is the command prompt where you enter your MATLAB
statements. This is indicated by the following prompt sign: >>
(c) Workspace: This area contains the names of the variables that you have defined in
MATLAB command window or that you have imported from other files. These variables
are available for you to process and explore.
(4) Command History: This area keeps track of the statements that you have entered so far
in the MATLAB command window.
To exit MATLAB desktop, you close the window by clicking the Close button on the top-
right comer of the desktop or by simply typing exit or quit on the command window.
Interaction with MATLAB can be accomplished using some of the following objects:
1. Statements and variables
2. Matrices
. Graphies4, Scripts
5. Input and Output Statements
6. Reading and Writing of Data Files
Figure 1.1: MATLAB Desktop
3.1.1 Statements and Variables
A simple MATLAB statement can be written as follows:
»
2%
where >>” is the MATLAB command prompt, & is the variable and the statement ‘A = 2°
initializes the value of A to 2. This statement is executed by pressing the ENTER (or carriage
return) key. If the statement is followed by a semicolon (;), the display of the output is
suppressed after the ENTER key is pressed.
Mathematical operations can also be performed in MATLAB. For instance, the results of
b? = 4ac where a = 1, b
4,andc = 3 can be obtained using the following statements:
al
Note that in this example MATLAB displays the results using the variable name ‘ans’. This
can be changed by assigning the variable name di to the expression. Henceforth, pressing the
enter key will not be explicitly denoted in the examples.
The commonly used mathematical operators are given in Table 3.1.
Table 3.1 Mathematical Operators
Symbol Description
+ | Addition
— | subtraction
* | Multiplication
7 | Division
‘ “Raised to the power of”
These operators can be used to perform various mathematical operations in MATLAB as
illustrated below:
MATLAB Statement Description
T
>> 1/4 z
0.2501 1
zee
2
4-9K5
Furthermore, most of the elementary mathematical functions are available in MATLAB. To
see a complete list of these, type in the following in the command window:
oo help elfun‘The use of some of these functions is illustrated as follows:
MATLAB Statement
Description
>> pind (30)
0.5000
>> acosd (0.6)
53.1301
>> exp (0.8)
5
poe 4p we ep ae
>> y = a * cosh(x/a)
Sine of angle 30°
Aresine of 0.6
The evaluation of the expression y = a cosh(®) whsre h=
gw=6r2mda=2
The evaluation of the expression b = gV3 where g = 9.8.
In addition to the elementary mathematical funetions, MATLAB has many other built-in
functions. Information on these can be obtained from the MATLAB Help menu, by pressing
the Fl key on the keyboard or by typing he1p and then the name of the function that you
intend to get information about. For instance, in order to get information about the clear
function in MATLAB, you may type in the following statement:
>> help clear
So far, we have been using single letters as variable names. MATLAB permits the use of
variable names that are a combination of numbers, letters, and underscores so long as the
names start with a letter (although it only remembers the first 63 characters or
namelengthmax). The variable names in MATLAB are also case sensitive. Moreover,
certain variable names have predefined values (which are changeable but it is better to avoid
changing them). Consider the following MATLAB statements:
MATLAB Statement
Description
>> namelengthmax
63
>> pi
3.1416
>> Int
‘The maximum length of a variable name or
function name that MATLAB remembers.
‘The value of
+02 (positive infinity)ans = Not a number (signifies a mathematically
New undefined value eg. the result of 0/0)
>> 34 45
ans = ‘Complex number with a real part of 3 and an
3.0000 + 4.00008 imaginary part of 4: note that j= V=T is
predefined. Ina similar manner, i
00 + 3.00008
This statement and the next few ones are 10
illustrate the variable name and function
<2 name sensitivity of MATLAB.
a-
3
>> sind (35)
0.57 :
>> stb (35) That is, sind( ) is an inbuilt MATLAB
Undefined function 'SIND' for input | fiuetion but SIND() isnot
arguments of type ‘double’.
MATLAB saves the values of the variables that are defined by the user in what is called the
workspace and these variables are available for later use. The who function (or the whos
function — for a more detailed list) can be used to list the variables that are currently in the
workspace. To illustrate, consider the following MATLAB statements:
MATLAB Statement Description
>> who
Your variables are
Aa oansb oc d@ g h wo x y
>> clear g
33 who Removes the g variable from
Your variables are workspace
aoe b ec d@ kh w 8 y
>> clear Removes all variables from
>> who workspace
>> ele Clears the command window
Although computations in MATLAB are performed in double-precision floating-point
number format, the default display is four decimal places. The output format can be altered
using the format function but the alteration does not change the internal MATLAB
computation. The use of the format fisnetion is illustrated as follows:
>> pi
3.1416
boy = sin(pi/3)>> formar long
>> pi
3.141592653589793
>> y = sin(pi/3)
vs
0.866025403784439
zmat sho
0.8660
>> format long @
SS pi
3.141892€53589793<+00
660254037844386.
>> format she
>> pL
0.8660
>> help format
format Set output format.
3.1.2 Matrices
In MATLAB, a typical matrix expression is enclosed in square brackets, column elements are
separated by commas or blank spaces, and rows are separated by semicolons or by pressing
the ENTER key. Consider the following matrix operations in MATLAB (we have to keep in
mind the requirements of matrix dimensions when performing matrix operations, of course)
2: 7 91
104
ae wel se ate 9)
ros) oH 445)
>> A= [1 25 sart (5)
log (12) 1og10(6) sin(pi/S)r acos (0.8) exp(2.1) 445i
1.0000 + 0.0000 + 2,00 2.2361 + 0
2.4849 + 0.7782 + 0,00 0.5878 + 0.00
0.6435 + 8.1662 + 0.0000i 4.0000 + 5.00
>> ce [2 3) ‘Generates a vector y whose ents are the sine ofthe entries of vector x
It should be noted that matrix computations that are accomplished by element-by-element
matrix operations (such as C + D, Cx D, C./D, C.\D in our example) are often called array
operations. In the above examples, notice the creation of the vectors b and x by defining the
start values (values of the first entry), the increments and the final values (values of the last
entry). Moreover, it is not necessary to include the square brackets when creating a vector
using the colon notation in MATLAB (that is, the statement x = [0:0.2:2] is the same
-2:2), Also, the computation of the elements of vector y where y = sin.x and
x is a vector is also possible in MATLAB. The selection of specific entries of vectors or
matrices is illustrated as follows:
asx =
MATLAB Statement Description
0.8000 1. 2000
Selects the first three elements of vector g0.2000 0.4000
000
47.345)
Selects the second element and then in the
increments of two until the fifth element
is reached,
Selects elements in rows 1 to 2 and
columns 2 to 3 in matrix J
Selects the clement in the second row
and the third column in mawix J
3.1.3 Graphics
When the plot fumetion is used in MATLAB, a graphical display called ‘Figure’ is
automatically activated. The graphical display can also be created by simply typing figure
in the MATLAB command window. For illustration, consider the following MATLAB
statements:
MATLAB Statement Description
>> x = [920.1220];
>> y= 5 * coal):
>> plot (x,y) A figure showing the plot of x versus y is displayed and
> MATLAB calls it Figure 1
> ‘Anew figure, called Figure 2, is created.
gure (1)
[020.1330];
exp(-0.1*x) .*c08 (x) +
>> plot (x+y)
>> title (‘Plot of y versus x")
>> xlabel ("x axis!)
>> ylabel ("y axia')
>> grid
‘Anew figure, called Figure 5, is created
This makes Figure | the current figure in display
(Clears the current figure
Compute the value of elements of vector y using the fornmala
y= eH cosx
Puts ‘Plot of y versus x’ atthe top of the plot
Labels the x-axis with ‘x-axis
Labels the y-axis with ‘y-axis'
Grid lines appear on the current figure
Other usefull functions that you could use to improve the quality of your plots include
Legend, text, subplot, ete. OF course, you could get more information on these and
others using the hep function; for instance, you may try the following:
383S help iegend
>> help text
5> help subpl
Also, a single figure can be used to obtain multiple plots. Consider the following statements:
MATLAB Statement Description
>> close all
[or0.1:3077
exp (-0.14x1) .*sin(x1); yy =e sin ey
[020.25
* exp (-
>> plot (x1,y1,"
>> grid
>> legend(‘yl vs
07
+05*x2) . ¥c0s (x2)
*,x2,y2,"m-—")
x1’, "y2 ve x2")
Ya = 2098 cosx,
Other plot functions available in MATLAB include semilogx, semi logy, loglog, ete.
More information on these, for instance, could be obtained by the following statements:
> semilogx
emi logy
logleg
help
help
help
3.1.4 Scripts
When the work to be performed in MATLAB is short and non-repetitive, one can easily work
with the MATLAB command prompt as we have been doing so far. However, using
MATLAB scripts, known as m-files (so named because the file names end with ‘n’), can
greatly simplify our work — particularly in the execution of long sequence of commands;
‘moreover, in this case, errors can easily be corrected and new MATLAB statements can be
added without the need for us to re-type a whole work. M-files are ASCII text files that are
created using text edifors and MATLAB has many built-in m-files. An m-file can easily be
created by clicking ‘New Script’ on the MATLAB home menu or by holding down the Ctrl
‘key and then pressing the letter N key on the keyboard (that is, Ctrl +N),
A script can be invoked, or called, in MATLAB by simply typing its name in the command
prompt of MATLAB. Moreover, a script can also invoke other scripts and MATLAB
functions. Suppose we would like to plot the function y = 2e~®
30 seconds for various values of oc, we would create a script and save it as plotfuny.m. The
following MATLAB statements could then be typed into the seript and saved:
“cost as t varies from 0 to
plotfuny.mction ¥ = (6) *exp (alpha*e)
this seript, define alpha in the workepace
and type plotfuny in MATLAB command window.
& This statement creates the time vi
2texp (~alpha*t) .*cos(t)+
plot(t,y)
xlabel ("7
% This statement labels th
% This statement turn on the grid line
‘Now, type the following statements in MATLAB command window:
> clear all
>> alpha = 0.05;
>> plotfuny
>> alpha = 0.1;
>> plotfuny
>> alpha =
>> plotfuny
You would notice that MATLAB uses the most recent value of alpha in the workspace when
plot funy is invoked, Also, notice that the symbol % has been used to add comments to the
MATLAB script (that is, MATLAB ignores everything on a line after it reads the symbol ®%).
Also, when the help funetion is invoked for the script, MATLAB displays only the first few
comment lines of the seript; that is,
>> help plotfuny
This script plote the function y
2cos (t) *exp (-alpha*t)
To use thie eeript, define alpha in the workepace
and type plotfuny in MATLAS command window.
3.1.5 Input/Output Statements and Reading/Writing Data Files
The save function in MATLAB could be used to store all the variables in the current
workspace in a single binary file called mat-file. The creation of a mat-file in MATLAB is
illustrated using the following example:
>> clear all
[020.1:2015
5 * cos(x);
exemple 1Here, the variables x and y have been created and stored in a file named example _1 anda
file named example_I.mat should now appear in the list of files in the Current Folder pane of
the MATLAB desktop. The load function could be used to retrieve the data stored in a mat-
file, To illustrate the use of the Load function, continuing from the previous example,
consider the following statements:
>> whos
Nane Bytes Clase Attributes
x 1608 double
y 1608 double
>> clear all
>> whos
At this point, no variable exists in the workspace since they have been deleted by the clear
function. Now,
>> load example_1
>> whos
Name size Bytes Class Attributes
x 1x201 1608 double
y 1201 1608 double
With this, the variables are now loaded from example_1.mat back into the workspace
Furthermore, the function input can be used to request or prompt for user input in
MATLAB. Also, the disp function in MATLAB can be used to display the value of a
variable. For instance, the following MATLAB script, named sum_x_and_y.m, prompts the
user for the values of x and y, and then computes and displays the value of z which is defined
asz=x+y:
sum_x_and_y.m
© enter the value of x and y
z, that is, 2= x+y
& This scrip!
© and displa:
disp (2)
Of course, the script can be run by simply typing sum_x_and_y and pressing the ENTER
key in the command window of MATLAB.
41In addition, itis possible to read real-world data from data files that are not in mat form. The
process involves mainly three steps, namely:
(a) Open the file using the fopen function
(b) Read the amount of data that is required. This could be achieved using the fget1
function (the £yet1 function reads a line from a data file and it has to be used a number of
times depending on the number of lines to be read from the data file) or the fscanf
function,
(c) Close the file using the £close function
Consider that we would like to read the data from a plain text file called example_2.txt which
has the following content:
example_2.txt
“very morning in Africa a gazelle wakes up.
Tt knows it mist outrun the fastest lion or it will be killed.
Every morning in Africa 4 lion wakes up.
It knows it must outrun the slowest gazelle or it will starve.
It doesn’t matter whether you are a lion or a gazelle
— when the sun comes up, you'd better be running.”
(A poem attributed to Richard Hodgetts)
The example_2.txt file can be created on a regular Windows PC by simply typing the above
content into Notepad (which can be found by clicking Start, the Accessories, and then
Notepad) and saving it in your Current Folder on MATLAB desktop with the file name
example_2. The following MATLAB statements demonstrate how we could retrieve the first
three lines of the content of example_2.txt:
“Every morning in Africa a gazelle wekes up.
>> second line - fgeti (example 2 fid)
second_line =
It knows it must outrun the fastest lion or it will be killed.
>> third line = fgetl(example_?_fid)
third line
Every morning in Africa a lion wakes up.
>> felose (example 2 fid)
°Here, the number returned by calling the fopen function is 3. According to MATLAB
documentation, it could be any number but not 1 and 2. The file identity number (or, file ID)
is stored in the variable name example 2 fid which we chose; if the file ID is equal to
=1, then there is an error in opening the file. Also, it should be noted that a new line is
retrieved each time £get1 is called and if a line is empty, a call by Eget1 displays '* (not
shown here since our statement in example_2.txt began right from the first line). Also, note
that to close the file, we used fclose(example 2 fid) and not
fclose (‘example 2.txt') as we would be tempted to do
The fopen and the fprint £ functions in MATLAB could also be used to write into a text
file. The following MATLAB code are used to demonstrate this:
>> t = 010.25:10
SS y = Qtexp(-0.05¢t) eos (t)7
>> z= [tr yl:
ample_3 fid = fopen(*example 3.txt', 'w");
ample 3 fid, ‘Sf $£\p
3 fia);
ose (example
Inusing the fopen function in this example, 'w" indicates that we are opening the file for
writing. You may wish to use he1p fopen statement for more information on this. Also, in
using the fprint £ function, '£ %£\n' indicates to MATLAB to write the first entry of
the first row of z into the file example_3.txt as a floating point aumber at the location of the
first 8 and to write the entry of the second row of 2 into the file example_3.txt as a floating
point number at the location of the second $£; the \n indicates ‘move unto the next line’
Try removing '\n' to investigate the contents of example_3.txt file with and without it. You
may wish to use help fprinté statement for more information on the fprint£
function. Thus, this example creates the example 3.txt file in the Current Folder of
MATLAB (You can double click on it to view the content but ensure the file is closed using
fclose(example_3_fid), for instance, before doing this).
Note:
1. For seripts, mat-files, text files or other files that you have ereated for use in MATLAB, do
not forget to be working in a directory or folder that you have created or you have the
permission to create and save files into.
2. You may wish to save each of your MATLAB lab sessions using the diary function of
MATLAB. Use the help diary command for more information on how you may do this.
3. It is important to ensure that the plots you create always contain titles and the axes are well
labelled. A plot should also contain a legend if multiple graphs appear on the same figure.
B3.1.6 Examples
1. An object (of negligible mass) is to be hung from the end of a pole supported by a cable as
shown in the figure below
Figure Ex 1
The pole is attached to the wall by a pivot and the cable is 8 metres long. A decision needs to
be made where on the pole to attach the cable. Ifthe cable is attached at a distance d from the
end and the mass of the object is object 20 kg, the tension in the cable is given by the
following expression:
20x 9.81 x8x8
dx Vo4=d?
Plot a graph of cable tension 7 versus attachment point d. Use this to find the optimal point of
attachment to minimise the tension in the cable.
SOLUTION
Problem analysis:
2oxo.a1xexa
Formula: T = “S228
alee
Input: d
Output: Plot of T versus d (we are required to deduce the value of d for which
T is minimum — that is, the optimal point of attachment — from this
plot)
Pseudocode:
Step 1: Define the elements of vector d
“4Step 2: Calculate the elements of vector T
Step 3: Plot and display the graph of d versus 7
(Note that d versus 7 or T versus d are the same except for the choices of the axes’ names).
Lastly, deduce the optimal point of attachment from the displayed graph.
The MATLAB code to implement the algorithm described by this pseudocode is as follows:
ndow
les fz
the command
all the varii
sly, the cable mu:
meters. Thus, I'll c
oll:
length (a); &
e4*ones(1,a
te aze all ones.
+81*8*8) ./ ("sqrt tb —
' finds the Leng!
function ‘ones (m,n)" ox:
an m-by-;
maybe
3:
8 -
plot (a, 7) +
xlabel(' nce, a");
ylabel (*Tension, T*)?
title('A plot of d vers
By looking at the graph, it would be acceptable as an answer to indicate that the minimum
value of d for which the value of 7 is minimum lies between d = 4 and d= 7. However, by
zooming in the displayed figure (by clicking the ‘zoom in’ button on the menu), it can be
determined that the value of d for which 7 is minimum is d= 5.657 and the value of T at this
point is 392.40 N.
2. Ifa projectile is launched with a velocity of 50 m/s at an angle of @ to the horizontal, the
horizontal and vertical positions (x, y) at time ¢ (ignoring the effect of the earth’s curvature
and air frietion) are given as follows:
x(t) = ut
yO = vt = Fgt?
45where u = 50cos 6, v = 50sin@ and the gravitational constant g = 9.81 nv/s*. The time at
which the projectile hits the ground is given as follows:
2
fina =F
Assuming that @ = 60°, plot the trajectory of the projectile.
SOLUTION
Problem analysis:
Formulae: x(t) = ut, y(t) = vt -Fgt? , tyinat u=50cos@, and
v=50siné
Input: @ = 60°, g = 9.81
Output: The trajectory of the projectile is the plot of x versus y
Pseudocode:
Step 1: Define @ and g
Step 2: Calculate the elements of vector ¢
Step 3: Calculate the elements of vectors x and y
Step 4: Plot and display the graph of x versus y
‘The MATLAB code to implement the algorithm described by this pseudocode is as follows:
50*sind (theta):
50*coad (theta)
2*v/a3
slitfinal;
ut,
vit - 1/24gte.*2e
4a
plot (x,y)
glabel (?
Label (*
tal Position, x (m)");
1 Position, y (m)");
46title (Prajecte
Notice that I have used ‘\theta’ with the title function in order for the symbol to be
displayed in its place. ‘theta’ is one of many so called TeX characters available in MATLAB.
‘You can search the MATLAB documentation for other Greek letters and mathematical
symbols that are available in MATLAB.
3. Consider a three phase signal formed by sin(¢), sin(t + 2/3) and sin(t + 4/3), plot
these three signals on a single graph for 0 < t < 20 where ¢ is in seconds.
In addition, from the three signals, a rectifier bridge produces a new signal that is the
‘maximum of the three components at any time. Plot the new signal.
SOLUTION: We may write the following MATLAB code to complete the given tasks:
SE
t= 1:0.1:20;
signal = ain(e);
signal? = sin(t+ 2*pi/3);
signal + 4*pi/3);
Figure (1 (t,signall,'b', tysignal2,'r', tysignal3,"k')
glabel ("Time (sec)')} ylabel(‘runction amplitude’);
title("Plots of Functions: sin(t), sin( /3) and sin(tt4\pi/3)"):
grid on
Legend("sin(t)', 'sin(tt2\pi/2)", ‘sin (t+4\pi/3)")
sealing 5]? axis (scaling) :
: t polishes our graph furth
: ‘help axis’
hold on tes to MATLAB that we shall still add
heck out with ‘help hold’
_ of signals
Rectified signal
& of the matrix.
Figure(1); plot (t,Rectified signal, 'mx');
title("Plot of the Unrectified and Rectifi
Legend (‘sin(t)'", "sin (tt + tsin(tt4\pi/3)*,
= That is, MATLAB replaces the old title and legend with thei
4. Consider the problem of finding the ‘optimal’ straight line (or, the line of “best” fits) that
describes a function that is given by a set of data pairs (x4. Yi), (Xa. Ya)e « «5 ns Ind.
Recalling that the equation of a straight line is given by y = mx +c and by minimizing the
least square error E which is defined as follows:the optimal value of m and c, denoted as moy- and Cope. respectively can be computed using
the following equations:
Cope = ¥— MoyeX
where ¥ and J are the mean values (arithmetic means of the entries) of veetors x and y,
respectively (that is, ¥ = ae andy - mye
Download the file noisydata.mat from the ‘Course Documents’ section of this module
(EG7012) on Blackboard and, using the data contained therein, complete the following tasks:
(a) Calculate the value of the slope and intercept of the optimal line through the data points.
(b) Caleulate the error for the optimal choice of m and c. Now try other (non-optimal) values
of m and c and calculate their errors for comparison with the optimal values.
(c) Plot a graph showing the original data points and the optimal line.
(Hint: You may find the following MATLAB functions helpful: length, mean, sum and
hold)
he MATLAB code for completing the given tasks may be written as follows:
whos % This is used to check the variables loaded into the workspace
8 Question a:
n= length (x) +
%_=mean(z); $ same a:
mean(y); © seme =.
= (sum(x."y) - nty,
9
=m optts_
& Question b:
Error - sum((y - mopt*x - ¢ opt).
m= 2; & che imal
cal imal intercept of the line
New_error = sum((y ~ m*x - c).*2)
% Question c:
figure; plot(x,y,"bx'); hold on
pt*xx + ¢_opt*ones(1, length (xx) )s
% Here, I've written
= Check out ‘help ones’ in MATLAB
plot (xx, y¥,'z")
label ('x'); ylabel('y');
legend (‘original date poi
ov form.3.1.7 Getting Help and Further Information
It should be clear by now that, because of the share volume of the in-built functions and other
capabilities of MATLAB, it will be impossible to cover every topic in this handout. As
mentioned previously, you may seek help in using MATLAB from the MATLAB Help
‘menu, by pressing the F1 key on the keyboard or by typing he1p and then the name of the
function that you intend to use. Two other helpful functions that are similar to the help
function that you may want to be aware of includes:
(a) the Lookfor function: this searches m-files for a keyword;
(b) the doc function: this opens the MATLAB Help browser.
Moreover, there are many websites that teach the basics of MATLAB that you could readily
use if you feel they would improve your understanding. For instance, examples of YouTube
videos that could be of help to you as learners are:
https:/www. youtube.com/watch?v=cyxFsSISxWwE ;
‘Attps://www. youtube.com/watch?v=VP1kCali3V0 ; and,
https://www. youtube.com/wateh?v=cLOdKEkuma0 .
3.2 Programming using MATLAB
In this section, MATLAB statements for the three methods of control in computer
programming (that is, the sequential, the selection aud the repetition controls) will be
presented. Each of these will be followed by examples to illustrate how it may be applied in
programming for problem-solving.
3.2.1 Sequential Control in MATLAB
Sequential control, as mentioned in Section 2.1, involves the execution of a program in
sequence. In MATLAB, it basically involves the definition of variables (that is, assigning
values to variables or equating the variables with functions that determines their values).
Consider the problem of approximating the speed of a satellite given in Section 2.1.1
(Example 1), given that k = 1.48 x 10"! m3/s? and = 4.3 x 10° m, the MATLAB code for
computing the speed, given by speed = /K/d , is as follows:
= 1.4e*10°L1:
& Defines d
49sare (e/a)
‘The answer to the problem is 185.5225 mis.
Also, consider the problem of computing the period of a simple pendulum given in Section
2.1.1 (Example 3), given that @ = 30° and | = 40 cm, the MATLAB code for computing the
period of the simple pendulum is as follows:
theta = g = 9807 1 = 40;
P = 2¢pitsqrt (1/q) * (141/44 (sind (thete/2))“2)
‘The answer to the problem is 1.2907 seconds,
3.2.2 Selection Control in MATLAB
Selection control, as mentioned in Section 2.2, refers to the execution of a program involving
the selection of one of several alternative set of statements. In MATLAB, the structure of a
simple selection control statement is as follows:
if expression
statements
end
A more general statement could be written as follows:
if expression
statements
else expression
statements
end
An even more general statement could be written as follows:
if expression
statements
elseif exprConsider the problem of computing the safe loading of a column given in Section 2.2.1
(Example 1), supposing that we are required to find the values of the loading | for s = 100
and for s = 270, we may write the following MATLAB code to complete this task:
100; 1 = 113800 - 2.275*s*2
270; 1 = 123400/ (13.75 + ((s*2)/17900))
However, a more clever way to tackle this task (that would address not only the task of
computing 1 for two values of s but) for any value of s would be to write a MATLAB script
similar to the following one which we have named compute_loading.m.
compute_loading.m
% This script computes the value of loading of a column(1) given the
§ slimness ratio = using the formular:
5 1 = 113800 - 2.2758°2 ifs <
s on
® 1 = 123400/ (13.75 (3*2/17900)) if
= To use this script, define @ in the workspace and type compute_loading
© in MATLAB command window.
if < 260
1 = 113800 - 2
1 = 123400/(13.75* (3*2) /17800)
& T have used thie form because
a equal to
y mumber that is not less that
ater than 260
Thus, the following statements could be typed in MATLAB command window to compute !
for various values of s:
>> s = 100;
>> compute _loading
Le
91050
>> a = 2707
>> compute_loading
1
2.2036e+03
>> 8 = 80;
>> compute loading
L-
99240
p> s = 3607
>> compute_loading
2 =
1.2395e+03Similarly, consider the problem of computing the roots of the quadratic equation ax? + bx +
¢ = O whieh can be obtained using the following quadratic formula:
—b + vb? = 4ac
=
2a
as given in Section 2.2.1 (Example 2). This problem could be solved by creating the
following MATLAB script named quadratic_roots.m.
quadratic_roots.m
This script find the roots of a quadratic equation ax"2 + bx + x
% using the quadratic formula. It also tells whether the roots az
: net, complex, or real and double.
&
% To use this script, the values of a, b and c have to be defined in
& the workspace
% Compute the determinant, d:
d= b%2 - dtate;
message_l = ‘Roots are real and distinct";
: aractera az ite value
message 2 2
message 3 2
(-b + sart (d))/(2+a)
(-b ~ sart (4) )/(2+a)
disp(message_1)
elseif d <0
eal_part_zl - -b/(2*a)
imag_part_x1 = sqrt (abs(d))/(2*a)
real_part_x2 - -b/(2*a) % Note: Here, T
& real_part_x2
~sqrt (abs (a) ) / (2*a)
30 write
part_xl
imag_part_x2
disp [message
else
dap (meseage_3)
end
‘As would be expected, the following statements could be typed in MATLAB command
window to compute the roots for the various values of a, b and c:
ppas3pb= 1% 6
SS quadratic roots
al
0.1743~3.8357
Roots are real and distinct
asl b=% c= 3;
>> quadratic roots
real _part_xl =
imag_part_x1 -
1.4142
real_part_
imag_part_x2
~1.4142
Roots are complex roots
ay
ppasil;pb= 26
35 quadratic roots
xL
Roots are real and double
3.2.3 Repetition Control in MATLAB
Repetition control (or the for-loop), as mentioned in Section 2.3, refers to the execution of a
program involving the repetition of one or more statements and there are two types: the
counter controlled repetition and the logical controlled repetition loops.
For the counter controlled repetition loop, the control loop is executed a pre-specified number
of times, The control variable keeps track of the number of times the loop has been executed
at any given time. In MATLAB, a counter controlled repetition structure can be stated as
follows:
for control variable ~ start value : increment : stop value
statements
end
The control variable could also be stated as a vector in MATLAB so the counter controlled
repetition statement could be written as follows (assuming the number of repetitions, or
iterations, required is n):
for control variable - [entry I entry
. entry_n]
statements
end
Consider the problem of displaying the numbers 1 to NV and their squares as given in Section
2.3.3 (Example 1), given that N = 7, the MATLAB code for obtaining the required result
may be written as follows:
tifor i=i
disp (i)
dip (i*2)
end
It should be noted that if the step size is 1, the statements i=1:1:N and i = 1:N are equivalent
in MATLAB. Moreover, the following MATLAB code could also be used to obtain the same
result:
ris (2294567)
disp (i)
disp(i*2)
end
As for the logical expression controlled loop (or the while-loop), the control loop is executed
while the condition specified by a logical expression is true; in MATLAB, a logical
expression controlled repetition structure can be stated as follows:
end
Consider the problem of finding the smallest positive integer NV such that the sum
1+2434-0N
is greater than the value of k as given in Section 2.3.3 (Example 5), given that k = 100, the
MATLAB code for obtaining the required result may be written as follows:
end
disp (N)
disp (sum)
Note: Sometimes, the execution of a for-loop or while loop may cause your program to
misbehave (that is, to run indefinitely) due to an error in your code. You can stop the
execution of such a program by pressing the Ctrl and the C keys together (that is, press Ctrl +
oO.3.2.4 Examples
1. For the projectile problem in Section 3.1.6 (Example 2), plot a number of trajectories of the
projectile for 0 < @ < 90 in order to investigate the range of variation of the projectile.
SOLUTION: Using the for-loop and choosing to plot 10 trajectories, we may write the
following MATLAB code to complete the given task:
g= 9.81;
Figure:
color_type = ['b*--" tr
eta = Ori
50*cosd (theta) +
50*sind (theta) +
2 yas
plot (x,y, co!
a= atl
end
label (’
Legend ("
2. The Fourier series approximation of the function f(x) =x for 0 > avg_of |
2.5000
jo_noe (2,3)
Write a MATLAB user-defined function that accepts three numbers and returns their sum and
the largest of the three.
SOLUTIOL
possible solution to this problem is as in the following MATLAB code:
sum_and_avg.m
function [sums, largest] =
ous - xt yt:
largest
if y >- laree:
largest
end
if z >= largest
ysThus, typing the following in sum_and_average(3,1,5) into MATLAB prompt, for
instance, gives the following results:
>> [sums, largest] = sum_and_avg(3, 1, 5)
It should be noted that when MATLAB scripts (that are not functions) are used, all variables
are added to the workspace (and they will over-write any existing ones with the same names).
However, when scripts are used in the form of functions, it is only the variables that were
accepted and/or those that were retrieved that will be are available in the workspace. In
general, in writing a user-defined function, the first line of the command statement in the
seript must with the keyword function in the format
function output = function_name (input)
Note: To use your user-defined functions, as with seripts, mat-files, text files, or other files
created for use in MATLAB, you should be working in a directory or folder that you have
saved the script of the funetion in, (Of course, you could use the addpath function to
circumvent this restriction if you want to)
3.3 Exercises
1. Let the following two-dimensional vector represent the population state of an island:
1
x= (i)
The first and second elements of x denote the fraction of the population in the west half and
the east half of the island, respectively. The state of the population after T units of time later
is given by the following equation:
new = AX
where
Pe 75 0.05
“10.25 0.95.
58Matrix A denotes the fact that a person in the west half stays put with the probability of 0.75
and moves east with the probability of 0.25 (thus, 0.75 + 0.25 = 1) and a person in the east
stays put with the probability of 0.95 and moves west with the probability of 0.05.
Consequently, successive population states can be computed by repeated matrix
multiplication.
(a) Calculate the population distribution after 7 units of time.
(b) Calculate the population distribution after 207 units of time.
(©) Plot the transition in the population over this period of time.
2. Consider the problem of finding the ‘optimal’ straight line (or the line of ‘best’ fits) that
describes a function that is given by a set of data pairs (xy. y1), (2+ Ya) = + + Qn» Yn)
Recalling that the equation of a straight line is given by y = mx + c and by minimizing the
least square error E which is defined as follows:
the optimal value of m and c, denoted as mope and Cope. respectively can be computed using
the following equations:
=2
Move = (Sx )-a*
Cope = I~ Moye
where ¥ and are the mean values (arithmetic means of the entries) of vectors x and y,
Diy). Write a MATLAB program which first
prompts a user for a sequence of data point pairs (x, y) and then plots this information
together with the optimal straight line which fits the entered data. The numerical values of the
optimal slope rope and the optimal intercept Cope should also be displayed in the MATLAB
command window.
respectively (that is, ¥ = 2 D7. x; andy
3, Write a MATLAB program which prompts a user to enter a positive integer and then tests
to ensure that a positive integer is entered (if not, a message should be displayed on the
sereen that prompts for another entry). The program should create an identity matrix of the
order of the integer without using the in-built eye function of MATLAB.
4. Check the fimetion of the rand in-built function of MATLAB and then use the command
*rand(5) to create a random S-by-5 matrix in MATLAB workspace. Write a
59MATLAB function of your own, with the name frob, that calculates and displays the so-
called Frobenius norm of matrix M using the following formula:
Frobenius norm of M =
(Hint: You may wish to use the size function of MATLAB to find n).
5. A projectile is to be launched by a marksman through an opening in a wall which is 40 m
away over a flat ground. The lowest part of the opening on the wall is 30 m above the ground
and the opening’s gap is 10m high as shown in Figure ExS. The mechanism for launching the
projectile generates an initial release velocity of 35 m/s. Ignoring air friction, the effect of
earth’s curvature, the physical size of the projectile and the width of the wall, use MATLAB
to find the range of appropriate launch angles so that the projectile passes through the
opening and plot five of the trajectories associated with these launch angles (which should
include the plots of the trajectories associated with the highest and lowest required launch
angles).
Hint: The equations of motion in the horizontal direction x and the vertical direction y are
given by:
x(t) = (vcos 8)t
yD = (vsinayt dot?
where v is the initial launch velocity, 9 is the angle of launch, and g = 9.8 m/s* is the
gravitational constant. Also, the time ty at which the projectile hits the ground is given as
follows:
avsind
a
u
10m
e's.
NN
|
30m
40mSee. 3.3 / Figure Ex5: The motion of a projectile
6. Monte Carlo Integration is a well-known technique for obtaining an approximation to an
integral using random numbers. Consider Figure Ex6 where we are interested in obtaining the
integral of a function f(x) between the limits [a,b]. The vertices of the rectangle
surrounding the region of interest, arranged in counter-clockwise order, are [a, 0], [b, 0].
[b,h] and [a, h]. Note that h = f(b). The shaded portion is the region under the function and
it is the integral we want to calculate. The Monte Carlo Integration proceeds as follows:
> Decide on the number of random points N that will be taken
> Using a computer code (written in MATLAB, for instance), generate NV random
points that fall within the rectangle
> Of these random points, count the number of points N, that fall under the function
(i.e. within the shaded region; you can assume that points that fall on the boundary
are within this shaded region)
- area.under the curve
> The theory says, the ratio “is approximately the ratio of —— ee for large
enough N. Therefore, f° f(x) * 4£x area of the rectangle
Write a MATLAB program to realize the Monte Carlo Integration technique just described to
integrate the function f (x) = x? where a = 2 and b = 9. The program should:
* Prompt the user for the number of random points WV to be taken. NV must be a positive
integer, otherwise, an error message should be displayed and the user is prompted to
re-enter the value of N.
‘* Prompt the user for the given values of the limits a and b. In your algorithm, make
sure all the NV random points fall within the rectangle whose vertices are [a, 0], [b, 0].
[b,h] and [a, hi}
© Display the value of the integral.
The exact value of the integral [Px?dx =| =
gral J vi,— 378
experiments to examine how the choice of the initial choice of N affects the accuracy of the
approximation.
= 240.3333. Perform some
Also, for the value of N = 3000, find the values of the integral for the values of the limits
[a, b] as follows: [2,7], [5,11] and [17,41]
(Hint: You can use MATLAB funetion rand to generate an array of random numbers whose
elements are uniformly distributed in the interval (0, 1))
aSec. 3.3 / Figure Ex6: The graph of the function f(x)
7. The function sin”* x, where || < 1, can be evaluated by the following infinite series:
cnty 2 so ay xent (an
PQnFD GPG AFD
anta
Write a MATLAB program to implement the above series up to and including the n‘ term,
The program should:
‘© Prompt the user to enter how many terms (i. the number of n) are to be caleulated
‘© Prompt the user to enter the value of x for which the calculation of sin x is required
‘© Apply the above series to caleulate sin” x
‘Print out the approximated values of sin~* x as each term in the series is added
Thereafter, you should use your program to estimate sin
series for the cases where x = 0.25, x = 0.5 and x = 0.75.
x using the first 5 terms of the
As you know, the value of sin~(2) is 2, Modify your program to determine how many terms
are needed in the series for sin~*(2) such that the error in the program is below 10-7 for
.14159265358979. You may have to use the long format in MATLAB by typing the
command format long, See MATLAB help for more information on format.
me
Note that:
o
1!
2B1=3x2x1
and, in general, nl=nx (n—1) x (n—2) xX X3x2x1.,
8. To obtain an approximate value for the integral of a nonnegative function y = f(x) from
x=a to x=), that is, f° f(x) dx, numerical methods are often used. One of these
mumerical methods is the trapezoidal method. In its simplest form, it involves dividing the
area under the graph of f(x) into n number of trapezoids each of width Ax such that Ax =
= The sum $ of the areas of these 1 trapezoids, which is the required approximate value of
the integral, can be defined as follows:
¢ Yot Yn
s= ax-(22449's)
=I
where y; =f). X41 = x1 + Ax and 1 is an integer; it should be noted that yp = f (0) =
F(A) and Yn = fn) = f(b). Hence, the algorithm for trapezoidal method can be deseribed
as follows:
Step 1: Define a, bn and the function f(x)
‘Step 2: Compute the increment Ax
Step 3: Set Sum = Oand.x =a
Step 4: For {= 1101 =n ~1, do Steps 5-7
Step 5: Setx =x + Ax
Step 6: Sety = f(x)
Step 7: Set Sun
=Sum+y
Step 8: Compute yo and Yn,
ot
Step 9: Compute S using S = Ax- (222 + swm)
Using the algorithm of the trapezoidal method described and taking n = 60, approximate the
values of the following integrals:
@) +x?) dx
Gi) Pxtax
B‘Your algorithm should prompt the user to enter the values of a, b, and n. It should also, at the
end of the calculation, display the approximate value of the integral.
As you are aware, the exact values of the integrals in ()) and (ii) are 120 and =,
respectively. Use these values to validate the correctness of your code and perform some
experiments to examine how the choice of m aflects the accuracy of your approximation.
Hence, find the approximate value of the following integral:
Sp NTF ax
9. It is very difficult and sometimes impossible to solve many differential equations exactly
but it may be possible to solve some of these equations using numerical methods. The Runge-
Kutta methods are an important family of a class of numerical methods and are one of the
most accurate for solving ordinary differential equations, Assuming that the solution to a
first-order differential equations y’ = = f(x,y) with an initial condition y(x = 0) =
y(Xo) = Yo is desired in the interval x9 Step 2: ‘12'— being the smallest in the list — is in the wrong position
Step 3: Put ‘12’ in the proper position (interchange positions 1 & 2)
The updated listis: x, = [12 83 71 57 90 40 31]
24 Scan — Step 2: 31'— being the next smallest — is in the wrong position
Step 3: Put 31° in the proper position (interchange positions 2 & 7)
The updated list is: x, = [12 31 71 57 90 40 83]
3rdScan> Step 2: ‘40° is in the wrong position
6Step 3: Put ‘40° in the proper position (interchange positions 3 & 6)
The updated listis: x3= [12 31 40 57 90 71 83]
Final Sean Step 2: '-»" is in the wrong position
Step 3: Put "in the proper position
The updated list is: Xpings = 12 31 40 57 71 83 90]
Thus, xsinai is the vector containing elements of x in ascending order. Write a MATLAB
program that sorts the entries of a given vector in ascending order using the selection
algorithm described (without using in-built sorting functions of MATLAB such as sort,
Assorted, sort row or similar). Your program should
- prompt the user to define the unsorted vector x or its entries;
- display the updated vector x; only if an update is made;
- display the sorted vector Xpinat
+ display the total number of updates performed by your program.
Test your algorithm by arranging the entries of the following vector in ascending order:
x= [83 12 71 57 90 40 31 40 22 67 4 78 19]
664. More on Programming Using MATLAB
More on scripts and functions: Functions as a special type of scripts; creating funetions in
MATLAB (e.g. other ways of writing MATLAB functions in one and the same script)
More on selection control: ‘case’ statement in MATLAB
More on ‘break’ and ‘continne” statements in relation to the ‘for-loop’ and the ‘while-loop’
Structures in MATLAB
Problem analysis,
MATLAB Statement Description
o5. Application to Commonly-encountered
Problems
Examples
- Sorting problems, ete.
Problem analysis,
Programming
MATLAB Statement Description
66. Application to Problems in Science and Engineering
- Numerical methods, integration, differentiation, root finding, ete.
~ Matrices and Linear algebra
‘More on Matrices: generate vectors with linspace funetion; selecting all column and all
rows in a matrix using (m,:) and (:.m); creating a submatrix using A((2 3], [2 4]) which
is the same as A(2:3.2:4); selecting the last column/row of a matrix e.g. A(end.2);
converting a matrix into a vector using A(:) command; more on using ‘end’ e.g.
A(end:-1:1,end); deleting a row/column using [ ] operator e.g. A(3,:) = [ ]; using size to
get the dimension of a matrix; continuation of a row using ... : concatenating matrices;
matrix generators (using eye, zeros, ones, diag, rand, ete.); special matrices (e.g. hilb,
invhilb, magic, pascal, toeplitz, vander, Wilkinson)
‘More on Arrays: Arrays (using /, .\.* and);
‘More on Matrix functions: - matrix functions (det, diag, eig, inv, norm, rank)
Applications: staties structural analysis,
- Differential Equations: structural dynamics, FEM, etc.
MATLAB Statement Deseription
©7. Miscellaneous Topics in Programming Using MATLAB
- Creating standalone programs using MATLAB
- Calling C/C++/Fortran/Java program functions from MATLAB
- Calling MATLAB functions from C/C++/Fortrar/Java programs
- GUI in MATLAB
Problem analysis,
MATLAB Statement
Deseription
70Answers to Some Selected Problems
Section 3.3: Exercise 1
aA
[0.75 0.05 0.25 0.95];
[2 ots
& (a) The population after T units of time
new = At
% (b) The population after 207 units of time:
§ Here, we need to compute xnew - 20 times - interatively
for T+ 1:20
xnew = Atx;
= The next two stetemente are need for (c) below
xwest (T) = xnew(1); % Pick the lst element of xnew and keep it
xeast (Tt) = mew(2); Pict the 2nd element of xnew and keep it
x = new; 3 Get ready for the next iteration
end
& (c) The plot of the transition over 207 units of time:
T= 1:20;
plot (T,xwest,
+), xeast, 'ex--")
& "Polishing’ the plot further:
xlabel('Units of time in T')
ylabel ("States of the population’)
legend(‘xwest', 'xeast', 2) % '2' here signifies the location to put the
legend; try 1, 3 & 4 to see the difference,
% or seek ‘help legend’.
Section 3.3: Exercise 2
i= 0; & counter
reply = "Y's
while reply -- 'Y'
a= atl
x(i) ~ input (‘Enter the value of x: ');
y(i) = input (‘Enter the value of yz ');
reply =input ("Do you want to input another value of (x,y)? ¥/N [¥]:',"s")z
if ivempty(reply) I| (reply == 'y")
veply = "7
§& I'm including small letter too just in case a user presses y
% instead of Y. Also, if a user presses ‘enter', it means YES
end
end
n= Length (x);
mean(x)7 $ same est x_
nean(y); % same ast y_
L/m* eum (x)
1/n* sum (y)
7mlope = (sum(s.*y) — n*y *=)/ (sum(e.*=) — =D
clopt = ¥_ - mopt*x_s
disp("The optimal value of m is:')
digp(m_opt)
diep("The optimal value of ¢ is:
diep(c_opt)
)
Figur:
plot (x,y, "bx")? hold on
(max (2942) 3
¥ I chose 2 here
% I could choose another number! All I wanted is a vector xx.
yy ~ mopt*xx + ¢ opt*ones(1, length (xx) )
% Here, I've written equation
plot (xx, yy, ="):
xlabel(‘x!)7 ylabel (‘y')7
legend('originel date points’, ‘optimal line’)
a straight line in vector form.
n