You are on page 1of 520

ESSENTIAL MATLAB

for Engineers and Scientists


Lecture given by:

Dr. Nay Zar Aung (Lecturer)


B.E (Mechanical, MTU), M.E (Mechanical, YTU)

M.E (Mechanical, ITS, Indonesia), Ph.D (Mechatronics, HIT, China)

Department of Mechatronic Engineering, YTU


Course Outline

■ Chapter 1 Introduction to MATLAB

■ Chapter 2 MATLAB Fundamentals

■ Chapter 3 MATLAB Programming

■ Chapter 4 Plotting Graphs and Curve Fitting Toolbox

■ Chapter 5 Using Symbolic Toolbox

■ Chapter 6 Numerical Analysis with MATLAB

■ Chapter 7 Creating Graphical User Interface with MATLAB (GUI)

■ Chapter 8 Converting MATLAB Code to Other Language Code

(Ccoder)
References

[1] HOLLY MOORE, “MATLAB for Engineers,” third Edition, Pearson,

2012, New York,

[2] BRIAN H HAHN and DANIEL T. VALENTINE “Essential MATLAB

for Engineers and Scientists,” fourth Edition , Elsevier , 2010.

[2] STEVEN C. CHAPRA, “Applied Numerical Method with MATLAB, for

Engineers and Scientists,”, second Edition, Mc GrawHill, 2005.

[3] PATRICK MARCHAND and O. THOMAS HOLLAND, “Graphics and

GUIs with MATLAB,” third Edition, CHAPMAN & HALL/CRC, 2003.


Teaching Schedule

Day Morning Afternoon


Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

*** 2 periods per week


*** 90 minutes per period *** 180 minutes per week
Teaching Schedule (Cont.)

Week Content
1 Chapter 1 Introduction to MATLAB
2
Chapter 2 MATLAB Fundamentals
3
4
5
Chapter 3 MATLAB Programming
6
7
8
Chapter 4 Plotting Graphs and Curve Fitting Toolbox
9
Teaching Schedule (Cont.)

Week Content

10 Chapter 5 Using Symbolic Toolbox


11
12 Chapter 6 Numerical Analysis with MATLAB
13
14 Chapter 7 Creating Graphical User Interface with
MATLAB
15
Chapter 8 Converting MATLAB Code to Other Language
16 Code(Ccoder)
Exam and Grading System

Task Marks Mark Grade

Assignment I 10% 75%-100% A+

70%-74% A
Assignment II 10%
65%-69% A-
Assignment III 10% 60%-64% B+
55%-59% B
Quiz 10%
50%-54% B-
Mid-term Exam 30% 42%-49% C+
40%-42% C
Final Exam 30 %
40% C-
Chapter 1

Introduction
Chapter Objectives

■ To get familiar with MATLAB by answering the following


questions,
What is MATLAB?
Why is MATLAB based on Matrix?
What can we do with MATLAB?
History to MATLAB?
How to install MATLAB?
How many MATLAB versions have been released?

■ To get familiar with MATLAB environment (MATLAB GUI)


What is MATLAB?

■ MATLAB stands for Matrix Laboratory.

■ It is forth generation technical computing and

programming language.

■ All the computations performed and programs

implemented in MATLAB environment are based on

matrix.
Why is MATLAB based on Matrix?

Date= [1 2 3 4 5 …31]

Day= [Sun Mon Tue Wed Thu Fri Sat]

Hour= [1 2 3 4 5 6 7 8 9 10 …. 24]

Second= [1 2 3 4 5…….60]

Fy r

Fx 
Rotation=[r  ]

Forces= [Fx Fy]
Why is MATLAB based on Matrix?

Location = [x y]

Location = [x y z]

Weight=[1000]

W=1000 kg
Why is MATLAB based on Matrix?

Mean=3
300

200

100

Diameter= [ 3 3.1 2.9 2.9 3 3 3 3 3.1 3.2 3 3.1 3 3.05]

90 6
120 60

150
2
30 Time= [7 8 9 10 11 12]
180 0 Wind= [5 6 5.5 6 5 6]
210 330
Diret= [45 30 120 180 0 35]
240 300
270
Why is MATLAB based on Matrix?

Fy3

Fy2
Fy1 3
1 2

Fx1 Fx2 Fx3


Tension  [Fx1 Fy1 ] F x2 Fy 2  F
x3 Fy3  ...

F
Distance = [2 4 6 8]
Shear force = [Fs1 Fs2 Fs3 Fs4]

x1=2 m x2=4 m x3=6 m x4=8 m


Why is MATLAB based on Matrix?

[1 2 3 4]
[0 90 180 270]
Why is MATLAB based on Matrix?

0
T6  A1 A2 A3 A 4 A5 A6 6
L6

5
L5
n x ox ax px  4
n oy ay py 
L4
3
T 
y

 nz oz az pz  L3
 
0 0 0 1 L2

1 2

L1

L0
Why is MATLAB based on Matrix?

1 2 3

Manhattan (Linear ) Cell  [1 2 3]


BSC

MSC 1 2 3

1 2 3
BSC 4 5 6
Cells  4 5 6
7 8 9
7 8 9

Manhattan (Square)
Why is MATLAB based on Matrix?

300

200

100
0 255
Why is MATLAB based on Matrix?

(x1,y1)
(x2,y2) 1 Interface =[ 1 2 3 4 5 6 7 ]
2
(x3,y3)
3 X=[x1 x2 x3 x4 x5 x6 x7 ]

7 Y=[y1 y2 y3 y4 y5 y6 y7 ]
(x7,y7)
(x4,y4)
4
6 (x6,y6)
5
(x5,y5)
Why is MATLAB based on Matrix?

Interface In Interface Out


in label out label
Cafe3
0 4 1 9
0 1 2 5 F
C
MPLS B
2
0
A 1
Cafe2
Cafe1

E
D

data label

IP address
What can We Do with MATLAB?

2x+5y-3=0 2 unknowns,
3x-4y+6=0 2 equations
Arithmetic +, -, , , x2

∫, d/dx
Calculus

100 unknowns,
sin(x), cos (x),
100 equations
Trigonometric tan (x)
What can We Do with MATLAB?

Cylindrical building

100 unknowns,
Block shape building 100 equations
What can We Do with MATLAB?

I’m a design
engineer.
What can We Do with MATLAB?

I’m a
physician.

Image processing by using MATLAB


What can We Do with MATLAB?

1
Without Cell Zooming
CCZ = Continuous Cell
Zooming CCZ with CPU
CCZ with TAPU

Transmitted power ratio


0.8
CCZ with LAPU

0.6

0.4
Day hours
Night
0.2 Night hours hours

0
12:00 5:00 a.m 10:00 a.m 3:00 p.m 8:00 p.m 12:00
Time of the day

Research papers Graphs


What can We Do with MATLAB?

Examples:

(1) Calculate the area of the following triangle with b=12 cm, h=12 cm, h=13
cm, h=14 cm, h=15 cm, h=16 cm, h=17 cm, h=18 cm, h=19 cm, h=20
cm.

(2) Calculate the area of the following circle with r=12 cm, r=13 cm, r=14 cm,
r=15 cm, r=16 cm, r=17 cm, r=18 cm, r=19 cm, r=20 cm.

r
h

b
History of MATLAB

■ MATLAB is the product of MathWorks.

■ It is started in 1984 and in 2000 it became popular in many areas.

■ Cleve Moler, Department of Computer Science, University of New

Maxico in the late of 1970.

■ Cleve Moler , Steve Bangert and Jack Little founded MathWorks.


MATLAB Versions

Version Year Version Year

MATLAB 1.0 1984 MATLAB 7.2


2006
MATLAB 2 1986 MATLAB 7.3
MATLAB 3 1987 MATLAB 7.4
2007
MATLAB 3.5 1990 MATLAB 7.5
MATLAB 4 1992 MATLAB 7.6
2008
MATLAB 4.2c 1994 MATLAB 7.7
MATLAB 5.0 1996 MATLAB 7.8
2009
MATLAB 5.1 MATLAB 7.9
1997
MATLAB 5.1.1 MATLAB 7.9.1
MATLAB 5.2 MATLAB 7.10 2010
1998
MATLAB 5.2.1 MATLAB 7.11
MATLAB 5.3 MATLAB 7.11.1
1999
MATLAB 5.3.1 MATLAB 7.11.2
2011
MATLAB 6.0 2000 MATLAB 7.12
MATLAB 6.1 2001 MATLAB 7.13
MATLAB 6.5 2002 MATLAB 7.14
2012
MATLAB 6.5.1 MATLAB 8
2003
MATLAB 6.5.2 MATLAB 8.1
2013
MATLAB 7 MATLAB 8.2
2004
MATLAB 7.0.1 MATLAB 8.3
2014
MATLAB 7.0.4 MATLAB 8.4
2005
MATLAB 7.1 MATLAB 8.5 2015
MATLAB Versions

Version Year Version Year

MATLAB 8.5
2016
How to Install MATLAB on PC

(1) Insert MATLAB software CD and open it


(2) Double click Setup icon to start installation
(3) Select “ Use File Installation Key”
(4) Select “ I have the file installation key for my license”
(5) Put serial No. 12313-94680-65562-90832
(6) Select “Activate MATLAB”
(7) Select “Activate manually without the internet”
(8) Browse license.lic
(9) Copy bin from Matlab32 or Matlab 64 then paste it to Files\MATLAB\R2014a
The MATLAB Desktop (Window)

MATLAB 7.04 (2005)


Starting MATLAB

2
The MATLAB Desktop (Window)

MATLAB 8.3 (2014)


Getting and Saving a New M-File

>> edit

_____.m Extension

name
Getting and Saving a New M-File

M-Files

Script M-file Function M-file

xxxxxxx function xxxxxxxxxx


xxxxxxxx xxxxxx
xxxxxx xxxxxx
xx xxx
xxxxx xxxx
xxxxx xxxx
xxx xxx
x x
xxxxxx xxxxx
xxxx end
Getting and Saving a New M-File

Script M-file Function M-file

% This program calculates the function [ Area ] = T_area( b ,h )

area of a % This program calculates the

% triangle with a height and base area of a

% given. % triangle with a height and base

b=input('Enter the base \n'); % given.

h=input('Enter the height \n'); Area=0.5*b*h;

Area= 1/2*b*h end

>> Tri_area >> T_area (12,8)


Opening a M-File

>> edit ________


Introduction to MATLAB (Cont.)
Comparing M-files
Importing Data
Creating a New Variable
Opening a Variable
Analyzing Program Code
Managing MATLAB Window
Setting Preferences
Getting Help File and Demo

Press F1

or

>> help

>> help sin


PLOTS
APPS
Recalling Previous Commands
Example Arithmetic Operations

>> 2+3 <Enter>


>> 5*4 <Enter>
>> 6^0 <Enter>
>> y=(6*3)-5+4^2 <Enter>
>> z=sqrt(y) <Enter>
>> sin(z) <Enter>
>>1/0 <Enter>
>> Inf+13 <Enter>
>> 29/Inf <Enter>
>> 0/0 <Enter>
Introduction to MATLAB (Cont.)

Existing MATLAB

Don’t do that !

>> quit

or

>> exit
Useful Commands

Command Task

>> edit To open a new script M-file

>> edit 'T_area' To open the M-file ‘T_area’

>> save To save the variables in the workspace


To save the variables in the workspace with a file name
>> save ‘Today’
‘Today”
>>save ‘Today’ x y To save the variables x and y in the workspace

>> save ‘Myprogram.m’ To save the M-file with a file name “Myprogram”

>> clear To delete all variables in the workspace

>> clear x y To delete the variables x and y in the workspace


Useful Commands

Command Task

>> cd(‘Myfolder’) To set “Myfolder’” as the current directory

>> clc To clear command window

>>home To let the command prompt to the upper left corner

>>help To start the help file

>> help function To know about corresponding function

>> help demo To start the example video file

>> lookfor “………” To look for the materials about “………”

>> quit or exit To stop the MATLAB


Chapter End Exercise

1. Get a new script M-file and save the file with a suitable name via
menu bar.

2. Type some arithmetic calculations (e.g., y=2+3, x=-9/4) in


command window. Then save the workspace with a suitable name
via menu bar or command window.

3. Manage the layout of MATLAB’s windows.

4. Try to get help file via menu bar or command window

5. Terminate the MATLAB.


Chapter 2

MATLAB Fundamentals
Chapter Objectives

■ To get familiar with MATLAB fundamentals answering the following questions


What are functions and commands?
What are operators, expressions and statements, variables?
How to give a variable name?
How is basic arithmetic operation in MATLAB?
How is operational precedence in MATLAB?
What are numeric array, character array, cell array and structure
array in MATLAB and how to create them in MATLAB?

■ To get familiar with basic math functions and matrix manipulation functions in
MATLAB
Functions and Commands

e.g., >> clc


>> clear
Commands
>> close
>> exit

>> date
e.g.,

>> sqrt(4) Functions

>> calendar
Operators, Expressions, Statements

Function

Operator

>> Y = sin(x) + b x, b, Y

Variables
Expression

Statement

>> 2*sin(x) (Expression)

>> Y= sin(2*x) (Statement)


Variables

>> a= 30 <Enter>
>> name= ‘Su Su’ <Enter>
>> Y2k= 2000 <Enter>

a= 30 name= ‘Su Su’

Variable Assigned value Variable Assigned character

1. It can contains “a-z”, “0-9” and “_”.


2. Start with an alphabet from “a-z”. It cannot be started with a number.
3. The number of characters must not be greater than 63.
4. It is case sensitive.
MATLAB’s Own Variables

Variable Name Explanation Example

When no variable name is >> 1/9


ans given, “ans” is used as a ans=
variable name. 0.1111
A built-in variable name that
pi represents  (=3.141593). >> 2*pi

A built-in variable name that


inf or Inf represents . >> 1/0

A built-in variable name that


nan or NaN represents Not-a-Number. >> 0/0

A known variable that is used >> 2+i


i,j for imaginary part of an
imaginary number.
MATLAB’s Own Variables

Do not Use Keywords as Variables

'break' 'if'
'case'
'otherwise'
'catch'
'parfor'
'classdef'
'continue' 'persistent'
'else' 'return'
'elseif' 'spmd'
'end'
'switch'
'for'
'function' 'try'
'global' 'while'
Arithmetic Operations

Algebraic MATLAB
Operation Example
form Expression

Addition a+b a+b 2+3

Subtraction a-b a-b 5-3

Multiplication ab a*b 8*1

Left Division ab a/b 3/4

Right Division ba a\b 3\4

Exponentiation ab a^b 5^2


Arithmetic Operations (Cont.)

MATLAB
Operation Example
Expression

Multiplication a.*b [8 1].* [1 5]

Left Division a./b [3 7]./[4 6]

Right Division a.\b [1 6 3].\[4]

Exponentiation a.^b [6 9].^2


Order of Operations in MATLAB

Order Operation

The First Parenthesis [ { ( ) }]

The Second Exponentiation (^)

The Third Multiplication (*) and Division (/ or \)

The last Addition (+) and Subtraction (-)

For same level , Left to Right

S= ((8*3)+5+6^2/3

Y= 3/4*5
Numbers in MATLAB

1. Decimal Notation (Fixed point)


1.2345 -381 0.0023

2. Scientific Notation (Floating point)


2.5000e+09 1.0000e-05

Mantissa Exponent

Minimum (realmin) Maximum(realmax)


0 
2.2251e-308 1.7977e+308
Formats in MATLAB

Format Command Example

Four decimal places format short 2.4486

Fourteen decimal places format long 0.11456734567009

Scientific notation with four decimal


format short e 2.0035e+10
places

Scientific notation with fourteen


format long e 6.666666666666666e-01
decimal places
Fixed or Floating point format with
format short g
four decimal places
Fixed or Floating point format with
format long g
four decimal places

*** If 0.001< x <1000, x is expressed in fixed point decimal format.


Formats in MATLAB (Cont.)

Format Command Example


Scientific notation with four decimal
format short Eng 666.6667e-003
places (Engineering style)
Scientific notation with fourteen
format long Eng 666.666666666667e-003
decimal places (Engineering style)
Hexadecimal format format hex

Rational format format rat 2/3

Two decimal places format bank 0.67

Sign format format + +


Suppresses excess line feeds to show
format compact
more output in a single screen.
Adds linefeeds to make output more
format loose
readable.
Mathematical Functions

Mathematical MATLAB
Explanation Example
Expression function

Calculate the sine value for


sin(x) >> sin (2/3*pi)
“x” with in radian unit.
sin(x)
Calculate the sine value for
sind (x) >> sind (120)
“x” with in degree unit.
Calculate the cosine value for
cos (x) >> cos (2*pi)
“x” with in radian unit.
cos(x)
Calculate the cosine value for
cosd(x) >> cosd (360)
“x” with in degree unit.
Calculate the tangent value for
tan(x) >> tan (pi/4)
“x” with in radian unit.
tan(x)
Calculate the tangent value for
tand(x) >> tand (45)
“x” with in degree unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the cotangent value


cot (x) >> cot (1/2*pi)
for “x” with in radian unit.
cot(x)
Calculate the cotangent value
cotd (x) >> cotd (90)
for “x” with in degree unit.
Calculate the secant value for
sec(x) >> sec (0.5)
“x” with in radian unit.
sec(x)
Calculate the secant value for
secd(x) >> secd(28.65)
“x” with in degree unit.
Calculate the cosecant value
csc(x) >> cosec (pi/3)
for “x” with in radian unit.
cosec(x)
Calculate the cosecant value
cscd(x) >> cosecd (60)
for “x” with in degree unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the sine inverse value


asin(x) for “x”. The result is in radian >> asin (0.5)
unit.
sin-1 (x)
Calculate the sine inverse value
asind(x) for “x”. The result is in degree >> sind (0.5)
unit.
Calculate the cosine inverse
acos(x) value for “x”. The result is in >> acos (1)
radian unit.
cos-1 (x)
Calculate the cosine inverse
acosd(x) value for “x”. The result is in >> acosd (1)
degree unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the tangent inverse


atan (x) value for “x”. The result is in >> atan (0.5)
radian unit.
tan-1 (x)
Calculate the tangent inverse
atand (x) value for “x”. The result is in >> atand (0.5)
degree unit.
Calculate the cotangent inverse
acot (x) value for “x”. The result is in >> acot(0.75)
radian unit.
cotan-1 (x)
Calculate the cotangent inverse
acotd (x) value for “x”. The result is in >> acotd(0.75)
degree unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the secant inverse


asec (x) value for “x”. The result is in >> asec (0.5)
radian unit.
sec-1 (x)
Calculate the secant inverse
asecd (x) value for “x”. The result is in >> asecd (0.5)
degree unit.
Calculate the cosecant inverse
acsc(x) value for “x”. The result is in >> acosec(0.75)
radian unit.
cosec-1 (x)
Calculate the cosecant inverse
acscd (x) value for “x”. The result is in >> acosecd(0.75)
degree unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the hyperbolic sine


sinh(x) sinh(x) value for “x” with in radian >> sinh (0.5)
unit.
Calculate the hyperbolic cosine
cosh(x) cosh(x) value for “x” with in radian >> cosh (0.25)
unit.
Calculate the hyperbolic
tanh(x) tanh(x) tangent value for “x” with in >> tanh (2)
radian unit.
Calculate the hyperbolic
coth(x) coth(x) cotangent value for “x” with >> coth (3.141)
in radian unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the hyperbolic


sech(x) sech(x) secant value for “x” with in >> sech (0.5)
radian unit.
Calculate the hyperbolic
cosech(x) csch(x) cosecant value for “x” with >> cosech (3.141)
in radian unit.
Calculate the inverse
sinh-1(x) asinh(x) hyperbolic sine value for “x” >>asinh(0.5221)
with in radian unit.
Calculate the inverse
cosh-1(x) acosh(x) hyperbolic sine value for “x” >>acosh(1)
with in radian unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the inverse


tanh-1(x) atanh(x) hyperbolic tangent value for >> atan (0.5)
“x” with in radian unit.
Calculate the inverse
coth-1(x) acoth(x) hyperbolic cotangent value >> cosech (3.141)
for “x” with in radian unit.
Calculate the inverse
sech-1(x) asech(x) hyperbolic secant value for >>asinh(0.5)
“x” with in radian unit.
Calculate the inverse
cosech-1(x) acsch(x) hyperbolic cosecant value for >>acosh(0.5)
“x” with in radian unit.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate exponential value


ex exp(x) >> exp(-0.5)
of x.
Calculate exponential value
ex-1 expm1(x) of x and minus 1 from the >> expm1(-0.5)
result.
Calculate natural logarithm
loge(x) or ln(x) log(x) >> log (0.5)
value of x.
loge(1+x) or Calculate natural logarithm
log1p(x) >> log1p(0.5)
ln(1+x) value of (x+1).
Calculate common (base 10)
log10(x) log10(x) >> log10(0.5)
logarithm value of x.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the common (base


log2(x) log2(x) >> log2(0.5)
2) logarithm value of x.
Calculate the square root
x sqrt(x) >> sqrt(4)
value of x.
Calculate the square root
x realsqrt(x) value of x. (Valid only for >>realsqrt(6)
positive values)
n
x Calculate the nth root value
nthroot(x,n) >>nthroot(8,3)
of x.
x Calculate the absolute value
abs(x) >> abs(-4)
of x.
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function
Calculate the angle between
real part x and imaginary part >> H=2-i;
 angle(H)
y. The resulted angle is >> angle(H)
radian.
Construct Create complex number by
complex complex(x,y) using x as real part and y as >> complex(2,3)
number x+yi imaginary part.
Construct
Create conjugate number of >>Z=4-6i
conjugate conj(Z)
a complex number Z. >>conj(Z)
number
Find real part
of complex Find real part of a given >> Z=4-6i
real(Z)
number complex number Z. >>real(Z)
Mathematical Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Find imaginary
part of Find imaginary part of a >> Z=4-6i
imag(Z)
complex given complex number Z. >>imag(Z)
number
Check Z if it is real or
Real number or
complex number. If real, it >> Z=4-6i
complex isreal(Z)
the result is 1 and if >>isreal(Z)
number?
complex, the result is 0.
Round to nearest integer for
Round towards
fix(x) a number by setting decimal >> fix(2.99)
nearest integer
numbers as zero.
Mathematical Functions (Cont.)

Mathematical MATLAB
Expression Explanation Example
function

Round to smaller integer for


Round towards
floor(x) a number by setting decimal >> floor(2.99)
smaller integer
numbers as zero.

Round towards Round to larger integer for a


larger integer ceil(x) number by setting decimal >>ceil(3.1)
numbers as zero.

Round towards Round to nearest integer for


>>round(3.4)
nearest integer round(x) a number by setting decimal
>> round(3.6)
numbers as zero.
Find reminder rem(x,y) Find the reminder of (x/y). >>rem(13,5)
Mathematical Functions (Cont.)

Mathematical
MATLAB
Expression Explanation Example
function

Find the reminder of (x/y) if


x and y have the same signs. >> mod(13,5)
Find reminder mod(x,y) The result is the sum of >> mod(-13,5)
reminder and denominator if
x and y have different signs. >> mod(-13,-5)

Check the sign of a number.


The result is 1 if the number >> sign(5)
Check sign of a
sign(x) is greater than 0, it is -1 if >>sign(-1)
number
the number is less than 0 and
it is 0 if the number is 0. >>sign(0)
Arrays: Matrices and Vectors

Matrix : An array of elements (numbers or characters) in rows and columns is


called a matrix. It is also called two dimensional array.

1 3 0 9
0 5 7 0  Su Su 
A  B  Character array
 4 1 4 8  Mg Mg 
 
6 0 7 2

Vector : A matrix that has one row and multiple columns or multiple rows
one column is called a vector.
0
  2
C  1 3  4 0 D 
5
 
7 
Scalar Matrix : A diagonal matrix with all its main diagonal entries equal is a
scalar matrix. W  1000
Arrays: Matrices and Vectors (Cont.)

Entry : The numbers or characters arranged in a matrix is called elements or entries


of that matrix.

1 3 0 9
0  Su Su 
5 7 0 B  Character array
A 
 Mg Mg 
 4 1 4 8
 
6 0 7 2

Index (or) Subscript: The row no. and column no. of an element or (entry) in a matrix
is called the index of that element. It is also called subscript.

A (1,1)= 1 C (2)= 3
A (2,2)= 5 C (4)= 0
Cell Array

Cell or Cell Array : In MATLAB, the array of matrices is called a cell.

   
 1 2 Kyaw Kyaw   1 2 Kyaw Kyaw 
   
A  A 
1 0  1 0 
4 3 [1 5 7]  [1 5 7]
  4 3 
 

Cell Indexing:

A {1,1}= [1 2] A {1,2}= Kyaw Kyaw

 1 0 A {2,2}= [ 1 5 7]
A {2,1}   
4 3
Structure Array

Structure or Structure Array :

Student
name

name
mark

mark
id

id
[75 80 21 66]
G1135
Mg Mg

G1037

[21 66]
Su Su
Structure Indexing : Student.name
Student.id
Matrix, Cell, Structure

Comparison

1 3 0 9  1 2 Kyaw Kyaw 
0 5 7 0  Su Su 
B A   

A  
 4 1 4 8  Mg Mg  Nyi Nyi [1 5 7] 
 
6 0 7 2

Matrix Cell
Kyaw Kyaw
09876
A [57 85 90]
Structure
Nyi Nyi
08991
[12 45 67]
Initialization Matrices and Vectors

1. Inserting directly the elements of a matrix at command window


>> A= [1 2 3; 5 9 0; 2 8 8]
>> A= [1, 2, 3; 5, 9, 0; 2, 8, 8]

2. Creating a matrix by using built-in function (just for special


matrices)
>> A= magic (3);
>> B= zeros(3,4)
>> C=linspace(0,2*pi,20)

3. Reading a matrix from a external file


>> A= xlsread (‘Mydata’)

4. Creating a matrix by using a M-file


Using Colon (:) Operator

1. We can create a vector by using colon (:) vector.

A= Start : Increment : End

A= [1:1:10]=1:10

B= [1:2:10]

2. The colon operator (:) can also be used to represent “all rows”
or “ all columns”. 3rd row
1st column
A (:,1) B (3,:)
All columns
All rows
Functions for Creating Special Matrices

MATLAB built-in function Example

ones (m,n) , ones (n) A=ones (3,2), B=ones (4)

zeros (m,n), zeros (n) A=zeros (1,2), B=zeros(4)

eye (m,n), eye (n) I=eye (3,2), I=eye (3)

diag(X) Y=diag(X)

magic (n) A=magic (5)

rand (m,n), rand (n) C=rand (2,4), A=rand (3)

randn(m,n), randn(n) A=randn(2,2), B=randn(2)

randperm(n) E=randperm(6)

randi(n) A=randi(10)
Basic Matrix Operations

Transposing:

Matrix transpose is changing row to column of a corresponding


matrix.

a b c  a d g 
A  d e f  A '  b e h 
g h i   c f i 

>> A = [ 1 3 6 7 9] <Enter>

>> A’ <Enter>
Basic Matrix Operation (Cont.)

Inverse:

A * B =C For matrices

A = CB
A-1 *A * B = A-1 * C

I*B = A-1 *C

B = A-1 *C

1
A 1  Adj A
det A

>> inv (A) <Enter>


Basic Matrix Operation (Cont.)

Determinant:

a b 
A  det( A )  ad  bc
 c d 
For 3  3 only

a b c  a b c a b  a b c a b
A  d e f  A  d e f d e  A  d e f d e 
 g h i   g h i g h   g h i g h 

det( A )  a e i  b f g  c d h  g e c  h f a  i d b
Basic Matrix Operation (Cont.)

Determinant:

+ - +
a b c a b c
A  d e f  A  d e f 
 g h i   g h i 

e f  d f  d e 
det( A )  a   b   c  
h i   g i   g h 

det( A )  a [ ei  fh ]  b di  fg  c [ dh  eg ]

>> det (A)


Basic Matrix Operation (Cont.)

Adjoint of a Matrix

a b c
A  d e f 
 g h i   e f d f d e 
 
 h i  g
 i  g
 h  
b c b c a b 
Adj A   
 h i  h
 i  g
 h  
 b c a c d e 
e f  d f  g h  
  
Basic Matrix Operation (Cont.)

Reshaping a Matrix

a c e g i
A  a b c d e f g h i j  A
b d f h j 
1 x 10 2x5

a, b, c, d, e

>> reshape (A, m, n) <Enter>


Basic Matrix Operation (Cont.)

Rotating (90) a Matrix

a b c  c f i 
A  d e f  A  b e h 
 g h i   a d g 

>> rot90 (A) <Enter>


Basic Matrix Operation (Cont.)

Flipping a Matrix Up and Down

a b c  g h i 
A  d e f  A  d e f 
 g h i   a b c 

>> flipud (A) <Enter>


Basic Matrix Operation (Cont.)

Flipping a Matrix Up and Down

a b c  g h i 
A  d e f  A  d e f 
 g h i   a b c 
B.C 1
x

y
Ti,j-1 Ti,j Ti,j+1

B.C 4 Ti+1,j B.C 2

1,1
B.C 3

>> flipud (A) <Enter>


Basic Matrix Operation (Cont.)

Flipping a Matrix Left and Right

a b c  c b a 
A  d e f  A  f e d 
 g h i   i h g 

>> fliplr (A) <Enter>


Basic Matrix Operation (Cont.)

Taking Elements from a Matrix

a b c 
A  d e f 
 g h i 

>> A (1,1) <Enter>


All rows
>> A(:,3) <Enter>
All Columns
>>A(3,:) <Enter>
Basic Matrix Operation (Cont.)

Extending a Matrix

A  1 2 3 4

>> A (1,5)=5 <Enter>

>> A(1,7)=9 <Enter>

A  1 2 3 4 5

A  1 2 3 4 5 0 9

A(1,6)
Basic Matrix Operation (Cont.)

Replacing an Element in a Matrix

A  1 2 3 4

>> A (1,4)=5 <Enter>

>> A(1,1)=9 <Enter>

A  1 2 3 5
A(1,1)
A  9 2 3 5

A(1,1)
Basic Matrix Operation (Cont.)

Cutting a Matrix

3 0 4 
A  1 2 3 4 B  6 2  1
5 5 7 

>> A (4)=[ ] <Enter>

>> B (1,1)=[ ] <Enter>

>> B (:,1)=[ ] <Enter>

>> B (5)=[ ] <Enter>

>> B (1:2:5)=[ ] <Enter>


Matrix Related Functions

Mathematical MATLAB
Explanation Example
Expression function

Calculate resultant of >> A = [3 4]


|| A || norm(A)
matrix A. >> norm(A)
>> A=[1 5 7; 3 4
Calculate the rank of a
Rank of a matrix rank (A) 9; 6 9 0];
matrix.
>> rank (A)
Calculate the determinant
Determinant det (A) >> det(A)
of a matrix.
Calculate the sum of
Sum of main
trace(A) main diagonal elements >>trace(A)
diagonal element
of a matrix.
Calculate the inverse
A-1 inv(A) >> inv(A)
matrix of a matrix.
Matrix Related Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate eigenvalues of a
Find eigenvalues eig(A) >>eig(A)
matrix.
Mention the numbers of
Dimension of a
size(A) rows and columns in a >> size(A)
matrix
matrix.
Length of a Mention the length of a
length(A) >> length(A)
vector vector.
Summation of a Calculate the sum of all >>sum(A,1)
sum(A)
vector elements of a matrix. >>sum(A,2)
Cumulative
summation of a Calculate the sum of >> cumsum(A,1)
cumsum(A)
vector elements of a matrix. >> cumsum(A,2)
Matrix Related Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Calculate the product of


Product prod(A) >>prod(A)
all elements in a matrix.
Calculate and mention the
Cumulative
cumprod(A) cumulative product of all >> cumprod (A)
product
elements in a matrix.
Calculate the mean or
Mean or Average >> mean(A)
mean(A) average value of elements
>>mean(A,2)
in a matrix.
Calculate the standard
Standard >> std(A)
std(A) deviation of elements in a
deviation >>std(A,1)
matrix.
Find maximum value in a
Find maximum max(X) >> max(A)
vector.
Matrix Related Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function

Find maximum values in


Find maximum max(X) >> max(A, [],2)
each row of a matrix.
Compare each element
from two matrices and
Find maximum max(X,Y) find maximum value. X >> max(X,Y)
and Y must have the same
dimensions.
Replace the
Replace the elements less
elements less than max(X,n) >> max(X,5)
than n in a matrix.
“n”
Find minimum value in a
Find minimum min(X) >> min(X)
vector.
Matrix Related Functions (Cont.)

Mathematical MATLAB
Expression Explanation Example
function

Find minimum value in


Find minimum min(X) >> min(X,[],2)
each row of a matrix.
Compare each element
from two matrices and
Find minimum min(X,Y) find minimum value. X >>min(X,Y)
and Y must have the same
dimensions.
Replace the
elements greater Replace the elements
min(X,n) >>min(X,2)
than “n” greater than n in a matrix.
Matrix Related Functions (Cont.)

Mathematical
MATLAB
Expression Explanation Example
function

Sort column-wise
Sorting in
sort(X) elements of a matrix >>sort(X)
ascending order
in ascending order.

Sort column-wise
Sorting sort(X, elements of a matrix
>>sort(X, ‘descend’)
descending order ‘descend’) in descending order.

Sort elements in each


Sorting row-wise
sortrows(X) row of a matrix in >> sortrows(X)
elements
ascending order.
Matrix Related Functions (Cont.)

Mathematical
MATLAB
Expression Explanation Example
function

Finding the Finding the indices of >> find(X)


location of non- find(X) non-zero elements in a >> find(X>3)
zero elements matrix >> find(X,2)

Finding the variance


Find the variance >> var(X)
var(X) of elements in a
of sample data >> var(X,1)
vector

Find the median of a >> X= [ 2 3 5];


Find the median median(X)
matrix or vector >>median(X)
Matrix Related Functions (Cont.)

Mathematical MATLAB
Explanation Example
Expression function
Find the minimum Find the minimum and
minmax (X) >> X=[1 -1 3 6 9];
and maximum maximum value of a
>> minmax(X)
values given vector or matrix.
Find the difference
between max and min >>X=[1 -1 3 6 9];
Find the range range(X)
of a given vector or >> range(X)
matrix
Produce all possible
Find all possible combntns(X) combination sets of >> A=[1 2 3 4 5];
combination from a given set of >> combntns(A)
elements.
Chapter End Exercise

Fill in the blanks.

1. A variable name may be as long as you like but MATLAB only


remembers_______________.

2. A subscript is indicated by ____________.

3. Statement in the same line may be separated by ___________.

4. MATLAB variable names are case _____________.

5. Use _____________ vector to remove elements from a matrix or


vector.
Chapter End Exercise (Cont.)

1. The final value of z from the program below is _________ .


a = 1:3;
b = 2:4;
z = sum(a.*b);

2. The final value of z from the program below is _________.


a = 1:3;
b = -2:-2:-6;
z = sum(a.*b);

3. The final value of z from the program below is ________.


A = [1 2 3 4; 5 6 7 8];
z = sum(size(A));
Chapter End Exercise (Cont.)

1. Write MATLAB expressions for the following mathematical


expressions.

1
(a) (b) 2 23 (c) 1.5 104  2.5 102 ( Use double
26 precision format)

2. (a) Add 1 to each element of the vector [2 3 -1]


(b) Multiply each element of the vector [1 4 8] by 3.
(c) Find the product of two vectors [1 2 3] and [0 ; -1 ; 1].
(d) Square each element of the vector [2 3 1].
Chapter End Exercise (Cont.)

3. Use MATLAB to evaluate the following expressions.


3 4 2
(a) 2 (b) (c) 2 2 (d) 23
56
(e) Find the sum of 5 and 3 divided by their product (Use rational format)
(f) Find the square of 2 (Use bank format)
(g) Find the tube root of the product 2.3 and 4.5.

4. If C and F are Celsius and Fahrenheit temperatures, their relationship is


F  9C / 5  32
Use the MATLAB command line to convert Celsius 37◦ (normal human
temperature) to Fahrenheit.
Chapter End Exercise (Cont.)

5. An amount of money A invested over a period of years n with an annual


interest rate r grows to an amount B. The formula is as follow.
B= A(1 + r)n
If A=1000, r=9%. What is total amount B after 10 years. Calculate it by
using MATLAB.

6. Use MATLAB to find the solutions of the following system of linear


equations.
10x-9y=100
-9x+20y-9z=0
-9y+15z=0
Chapter End Exercise (Cont.)

7. Find the total sum of the first eight numbers (i.e, N=8) by using the
formula and MATLAB function. Also find the mean and median.

N
N( N  1)
n  2
n 1

8. The factorial of “n” is defined as below. Find the factorial of 5 using the
formula and using MATLAB function.

n! = n (n-1) (n-2)…1
Chapter 3

Program Design
&
Algorithm Development
Chapter Objectives

■ To get familiar with MATLAB programming answering the following


questions,
What are the main components of a program?
What is program design?
What are the steps in creating a program?
What are M-file, Script M-file and Function M-file?
What is structure plan (or) pseudo code (or) algorithm?
What is flow control decision?

■ To practice MATLAB programming related to engineering applications


Components of a Program

Start

Input or Assigning 1

Working Statement 2

Output or Displaying 3

End
Program Design

Program Design: The designs of the components (input, output and working
statements) and related features of a program can be seen
as program design.
A program should

(1) fulfill the need of user and work well

(2) be convenient to be used

(3) be easy to be read,

(4) be easy to modify when required

(5) give less task to the user

*** All should be considered in designing a program.


Program Design

Example: Bicycle handle design


Program Design

Example:
Designer 1 Designer 2

Start Start Start

Assign base &


Input or Assigning Enter base & height height

Working Statement Calculate Area Calculate Area

Output or Displaying Display and Save the Display the Result


Result

End End End


Program Design

clc
clear

% This program calculates the area of a triangle. The base and


height of the triangle must be input by the user.

b=input('Enter the Base of the Triangle (m) \n');


Design 1
h=input ('Enter the Height of the Triangle (m) \n');

format bank
Area=0.5*b*h;

display (['Area =', num2str(Area), ‘ Square Meter'])


save Area

clc
clear

b=2;
h=3;
Design 2
Area=0.5*b*h;

display (Area)
Design Process

Step 1: Problem Analysis:


Try to understand the problem to be solved.
Step 2: Mathematical Description:
Collect the required mathematical equations to solve the problem.
Step 3: Define Input/Output Variables:
Define the input variables and output variables.
Step 4: Construct Structure Plan (Pseudo Code or Algorithm):
Write the list of the tasks in the program (Structure Plan).
Step 5: Transform to Program Code:
Write the program.
Step 6: Test and Apply the Program:
Test and use the program to solve the problems.
Structure Plan

Start
Read the input data b, h
Change format
Enter base & height
Calculate the area (1/2  b h)
Display the Area
Calculate Area
Save the Area

Display and Save the


A combination of English, mathematics,
Result
and anticipated MATLAB commands)
End
Example (Projectile)

Problem:

Plot the flight path (trajectory) of a golf ball that lunches


from the ground with an initial velocity (V0) of 10 m/s and angle
(0) of 45 until it reaches the maximum altitude.

Step 1: Problem Analysis:

x,y
x,y
x,y
ymax V0
0
x
Example (Projectile)

Step 2: Mathematical Description:


Collect the required mathematical equations to solve the
problem.

V0
t y max  sin 0
g

x  V0t cos 0 0 < t < tymax

g
y  V0 t sin 0  t 2 0 < t < tymax
2
Example (Projectile)

Step 3: Define Input/Output Variables:


Define the input variables and output variables.

V0= 10 m/s
Known (Input Variables)
0 = 45

tymax Unknown (Required Variable)

x
Unknown (Output Variables)
y
Example (Projectile)

Step 4: Construct Structure Plan (Pseudo Code or Algorithm):


Write the list of the tasks in the program (Structure Plan).

Read the input data V0, 0


Calculate tymax (tymax=V0/g*sin0)
Set 0< t < tymax with 0.001 increment (t=0:0.001:tymax)
Calculate horizontal coordinate x (x=V0 * t* cos0)
Calculate vertical coordinate y (y=V0 * t * sin0-g/2*t^2)
Plot x vs. y
Examples

Khin Cho Tun & Kunagorn (2015)

Pei Yu et. al., (2012)


Exercise

1. Write a Structure Plan or Pseudo Code or Algorithm for a program


that calculates the area of a trapezium.

a
h A=1/2 (a+b) h
b

2. Write a Structure Plan or Pseudo Code or


Algorithm for a program that works like a ATM
(Automated Teller Machine)
Exercise

3. Write a Structure Plan or Pseudo Code or Algorithm for a program


that calculates the area under the curve, f(x), between a and b, by using
Trapezoidal rule.

f(x)

a b

4. Write a Structure Plan or Pseudo Code or Algorithm for a program for


your research.
Exercise

1. Solution

Read the input data a, b, h


Calculate area (A=1/2*b*h)
Display trapezium area
Exercise

2. Solution

Read the user’s ATM card number


If the card number is correct, ask user’s password or pin code
If the password is correct, ask how much money he wants to
withdraw
Count the money in bin
If there is enough money in the bin
Give money to the user
If there is no enough money in the bin
Say “Sorry” to the user
If the password is not correct, say the user’s password
is wrong, let him try 3 times
If the card number is not correct, reject the card
Exercise

3. Solution

Read coefficients of f(x)


Read limits of area, a and b
Read number of divisions, n
Calculate the length of each division [(b-a)/n]
Calculate yn =f(xn) and yn+1 =f(xn+1) for every interval (division)
Calculate An=1/2*(yn+yn+1)*xn
Calculate total area under the curve An
Script and Function M-File

Script M-File

xxxxxxxxxxxx
xxxx
xxxxxxxx
xxxxxx
xxxxx
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
xxxxxxxxxx
xxxxxxxx

>> Name
Script and Function M-File (Cont.)

Function M-File

function [Output Arguments]= Name (Input Arguments)


xxxx
xxxx
xxxxxxxx
xxxxxx
xxxxx
xxx
x
x
x
xxxxxxx
end

>> Name (Input Arguments)


Script and Function M-File (Cont.)

Function M-File

function [Area]= Tri_area (b,h) function [Area, Perimeter]= Tri_area (b,h)


xxxx xxxx
xxxx xxxx
xxxxxxxx xxxxxxxx
Area= 0.5* b*h; Area= 0.5* b*h;
xxxxx Perimeter =………..
xxx xxxxx
x xxx
x x
x x
xxxxxxx b X b
end h end h

>> Tri_area (5,7) >> [x,y]=Tri_area (5,7)


Writing Comments

%% This program calculates

%%%___________________________

Gama=3; % Gama is path loss coefficient


Writing Comments

clc
clear

% %This program calculates the area of a triangle. The base and height of
%% the triangle must be input by the user.

% Reading Inputs
b=input('Enter the Base of the Triangle (m) \n'); % base
h=input('Enter the Height of the Triangle (m) \n'); % height

% Calculating the Area of Triangle


format bank % Changing format
Area=0.5*b*h; % Equation of triangle's area

% Outputting
display (['Area =', num2str(Area), ' Square Meter'])
save Area % Save workspace
Components of a Program

Start

Input or Assigning
?
Working Statement ?
Output or Displaying
?
End
Input and Assigning

For the variables that should be frequently changed

A= input (‘Enter the value of A \n’)

Name= input (‘Enter your name\n’, ‘s’)

For the variables that are fixed

A= 30;

Name= ‘Su Su’


Input and Assigning (Cont.)

To read a large data base from external files.

A=xlsread(‘Mydata',1,'A1:E5‘) 

[A,B]=xlsread(‘Mydata',1,'A1:E5‘) 

A=load(‘Mydata.txt’) 

A=load(‘Mydata.mat’) 

A=fscanf(file identifier, ‘format’)


Input and Assigning (Cont.)

fscanf

A=fscanf(file identifier, ‘format’)

A=fscanf(file identifier, ‘format’, size)

inf Read to the end of the file. (default)


N Read at most N elements into a column vector.
[M,N] Read at most M * N elements filling at least an M-by-N
matrix in column order. N can be inf, but M cannot.
Components of a Program

Start

Input or Assigning

Working Statement ?
Output or Displaying
?
End
Flow Control or Decision

If Statement

“if ” is mostly used flow control statement to let the program make
decision.

if Condition If Condition is true,


Statement 1 The program will work on
Statement 2 Statement 1, Statement 2 and so on.
Statement 3

… If Condition is not true,
… The program will neglect
end Statement 1, Statement 2 and so on.

if Condition Statement 1, end *** For only one Statment1


Flow Control or Decision (Cont.)

If Statement (Example)

Calculate y=x2 x<5

Relational
operator x=input('Enter the value of x \n');
Condition if x<5 if x <5

y=x^2 Statement y=x^2

end end
Flow Control or Decision (Cont.)

Relational Operators

Relation How to write


Description Example
operator in MATLAB

> Greater than > if A > B

< Less than < if A < B

 Greater than equal to >= if A>=B

 Less than equal to <= if A<=B

= Equal to == if A==B

 Not equal to ~= if A~=B


Flow Control or Decision (Cont.)

Logical Operators

Relation How to write


Description Example
operator in MATLAB

& AND & if A<5 & B>2

| OR | if A<5 | B>2

~ NOT ~ if ~ (A>B)

xor Exclusive or xor if A<5 xor B>2

&& Short-circuit AND && if A<5 && B>2

|| Short-circuit OR || if A<5 || B>2

*** a=0, b=sin(pi)


Flow Control or Decision (Cont.)

Example

Calculate y=x2 x=<5 x>10

Relational
operator x=input('Enter the value of x \n');
if x<=5 | x>10
Logical if x <=5 | x>10

y=x^2 operator y=x^2

end end
Flow Control or Decision (Cont.)

Exercise

1. Write a program to calculate and save the input/output variables for


the following relationships.
y=x2 for x<5
y=3x+5 for x=5
y=2x-3 for x>5

2. Write a program that can ask your name and tell you if your name
is match or not match with the name that it has known. Note that
the name it has known is “Kyaw Kyaw”.
Displaying Messages and Results

Simple Display

disp (‘Message’)

disp (Variable)

display (‘Message’)

display (Variable)

e.g.,

>>Y=[2 5; 6 7]; >>disp(X)

>>X=[ ]; >>display(Y)

>>disp(Y) >>display(X)
Flow Control or Decision (Cont.)

Example

   

     ?
   
 
   

   
    
    
        

   
 
    ?
 
   

   
    



  

?
   
Flow Control or Decision (Cont.)

Example
clc
clear
A=[1 3; 2 6];
B=[7 9; 0 -2];
C=[2 -1; 6 0];
MI=input('Enter your image \n');
if MI==A;
display ('It is Mr.A');
end
if MI==B;
display ('It is Mr.B');
end
if MI==C;
display ('It is Mr.C');
end
Flow Control or Decision (Cont.)

Example

Host A

150.215.017.009

Host B

192.168.3.1
Flow Control or Decision (Cont.)

Logical Function

Logical
Example Description
Function

if any(X) If any element in vector X is non-zero,

any(X) if any(X>6) If any element in vector X is greater than 6,

if any(X==1) If any element in vector X is equal to 1,

if all(X) If all elements in vector X is non-zero,

all(X) if all(X>6) If all elements in vector X is greater than 6,

If all(X==1) If all elements in vector X is equal to 1,


Flow Control or Decision (Cont.)

Logical Function

Logical
Example Description
Function

isnan(X) if isnan(X) if X is Not-a-Number (NaN),

isfinite(X) if isfinite(X) if X is a finite number,

isinf(X) if isinf(X) if X is infinity,

isempty(X) if isempty(X) if X is empty matrix,

isstr(X) if isstr(X) if X is a string,

strcmp(s1,s2) if strcmp(s1,s2) if string1 and string2 are identical,

isreal if isreal(X) if X is a real number,


Flow Control or Decision (Cont.)

Logical Function (Example)

Write a program by which a conveyor can check if there is a bag (or a


weight) on it.

[1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 0]
Flow Control or Decision (Cont.)

Logical Function (Example)

clc
clear
if any(A==1) A=input ('Enter the vector \n');
display('There are still bag(s)') if any(A==1)
end display('There is still bag(s)')
end
Flow Control or Decision (Cont.)

Example

Check a line of eggs and show a messages when is a cracked found.

1 1 1 0 1 1

1 2 2 2 2 2

A  1 1 1 0 1 1

A  1 2 2 2 2 2
Flow Control or Decision (Cont.)

Example

Logical
function
clc
clear
if any(A==0) A=input('Enter matrix A \n');
display ('There is cracked egg(s)') if any(A==0)
end display ('There is cracked egg(s)')
end
Flow Control or Decision (Cont.)

Example

Logical
function
clc
clear
if any(A<1) A=input('Enter matrix A \n');
display ('There is cracked egg(s)') if any(A<1)
end display ('There is cracked egg(s)')
end
Flow Control or Decision (Cont.)

Example

Motors Control unit


13

Parking
Info Park
Leave

Password
1 25

[0 444668 0 678902 55511 0 40111….]


Flow Control or Decision (Cont.)

Exercise

Write a program that monitors if there is spaces


or not in a parking.

This is no space in the parking.


Some space(s) left in the parking.
Flow Control or Decision (Cont.)

Nested if Statement

“Nested if ” is mostly used for multi-stage decision making.

if Condition1
Statement 1
if Condition2
Statement a
if Condition1
Statement b
if Condition2
end
Statement a
Statement 2
end
Statement 3
end



end
Flow Control or Decision (Cont.)

Nested if Statement (Example)

Write a simple program that works like a ATM (Automated Teller


Machine). The program should check the bank account number and the user’s
pin code (password) step by step. If two of them are corrected, the program
should ask how much money you would like to withdraw.

1. Insert the card


2. The machine checks the card
3. The machine asks the user’s pin
code
4. Then ask how much money the
user wants
Flow Control or Decision (Cont.)

Nested if Statement (Example)

clc
clear
BC=12460090956;
PC=123456;
BankAccount=input('Enter BankAccount \n');
if BankAccount==BC Condition 1
PinCode=input('Enter Pin Code \n'); Statement 1
Nested if PC==PinCode Condition 2
if display ('Slect the amount you want to withdraw \n') Statement a
end
end
Flow Control or Decision (Cont.)

Nested if Statement (Exercise)

Write a program that works like a random mobile


terminal performs soft handover.
Pr2
Pr1 
R 
Pr  PTx K  0 
 R
Pr3

Find
Flow Control or Decision (Cont.)

Nested if Statement (Exercise)


Flow Control or Decision (Cont.)

Nested if (Example)

Write a program to recognize the input image comparing with trained


image.
Flow Control or Decision (Cont.)

Else Clause

“else” is used together with “if ”. It is used for the last condition
without stating the condition.

if Condition
If Condition is true,
Statement 1 The program will work on
Statement 2 Statement 1, Statement 2 and so on.

else
Statement a If Condition is not true,
The program will work on
Statement b Statement a, Statement b and so on.
end
Flow Control or Decision (Cont.)

Else Clause (Example)

The load acting on a bar can be expressed with the following


mathematical equations. Write a program that describes the magnitude
of load at arbitrary distance x.
Lx=2x+5 for 0<x<5
Lx=15 for x5

x
Flow Control or Decision (Cont.)

Else Clause (Example)

Condition1 clc
clear
if x<5
x=input ('Enter an arbitrary distance, x \n');
Lx=2*x+5
if x<5
else
Lx=2*x+5
Lx=15
else
end
Lx=15
end
Else clause (No Condition)
Flow Control or Decision (Cont.)

Else Clause (Example)

Write a program that works like a TCP.


Flow Control or Decision (Cont.)

Else Clause (Example)

clc
clear
Datapack1=input('Enter the data package1\n');
Datapack2=input('Enter the data package2\n');
if (Datapack2-Datapack1)==1
display ('Yes, I have received properly')
else
display ('No, please send me again package2')
end
Flow Control or Decision (Cont.)

Else Clause (Example)

Write a program to check if a robot (a random mobile terminal) has


ever gone outside predefined area (convergence area) which is located at the
center of a rectangle region. Note that the predefined area has a radius of 10
m and the robot has moved 10 times in this case.

50 

  
-50  

-50 50
Flow Control or Decision (Cont.)

Elseif Clause

“elseif” is used together with “if”. It is used for checking multiple conditions.

if Condition1 If Condition1 is true,


The program will work on
Statement 1 Statement 1.
elseif Condition2 If Condition2 is true,
Statement 2 The program will work on
Statement 2.
elseif Condition3
If Condition3 is true,
Statement 3 The program will work on
else Statement 3.
Statement 4 If Condition1, Condition2, Condition3 are not
true, the program will work on Statement
end
4.
Flow Control or Decision (Cont.)

Elseif Clause (Example)

Write a program that guess the number and type of roots of a


quadratic equation (ax2+bx+c=0) according to its discrimenant, (b2-4ac).

Discrimenant
b2-4ac>0 two real numbers
b2-4ac=0 one real number
b2-4ac<0 two complex numbers
Flow Control or Decision (Cont.)

Elseif Clause (Example)


clear
clc
else if clause
a=input ('Enter coefficient a \n');
b=input ('Enter coefficient b \n');
if Disc>0
c=input ('Enter coefficient c \n');
display ('There are two real roots')
Disc=b^2-4*a*c;
elseif Disc==0
if Disc>0
display ('There is only one real roots')
display ('There are two real roots')
else
elseif Disc==0
display ('There are two complex roots')
display ('There is only one real roots')
end
else
display ('There are two complex roots')
end
Flow Control or Decision (Cont.)

Elseif Clause (Example)

Write a program to check if a random mobile terminal is in convergence


area of a cell.

-+ ++

500
700 -- +-
200 400

50
Flow Control or Decision (Cont.)

Elseif Clause (Example)

Write a program to check wheter two sensing areas of two robots (or
two sensor nodes) which are randomly moving are overlapping. Also, the
program should be able to mention the location of one robot (sensor node)
with respect to another one. The sensing area of each robot (sensor node) has
a convergence radius of 5 m and the area has a diameter of 100 m. The center
of the area is (0,0).

B
A 100
5m
Flow Control or Decision (Cont.)

Switch Statement

“Switch Statement” has similar function as if statement. Thus, it can be used


instead of if statement. The format is as follows.

switch Variable If Variable is the same as or equal to,


Assigned Value1, the program will
case Assigned Vale1 work on Statement 1.
Statement 1
If Variable is the same as or equal to,
case Assigned Vale2 Assigned Value2, the program will
Statement 2 work on Statement 2.

otherwise If Variable is not equal to,


Statement 3 both Assigned Value1 and Assigned
Value2, the program will work on
end Statement 3.
Flow Control or Decision (Cont.)

Switch Statement and if Statement

switch a if a==5
case 5 Statement 1
Statement 1 elseif a==6
case 6 Statement 2
Statement 2 else
otherwise Statement 3
Statement 3 end
end
Flow Control or Decision (Cont.)

Switch Statement (Example)

Using “Switch Statement”, write a program that works like a


voice recognizer for some specific tasks trained as follows. The
digits will be input by user in this example.

Open door – 01111001


Start engine – 1111110011
Play music – 111011011

Perform assigned
task

Receive Speaker Voice Digit to Compare with


Voice identification to digit character trained character
Flow Control or Decision (Cont.)

Switch Statement (Example)

clc
clear
Signal=input('Enter the digit \n')
switch Signal Variable
case 01111001 Assigned Value1
display ('Opening the door') Statement 1
case 1111110011 Assigned Value2
display ('Starting the engine') Statement 2
case 111011011 Assigned Value3
display ('Playing music') Statement 3
otherwise
display ('What can I do for you') Statement 4
end
Flow Control or Decision (Cont.)

Switch Statement (Example)

Interface In Interface Out


in label out label
Cafe3
0 4 1 9
0 1 2 5 F
C
MPLS B
2
0
A 1
Cafe2
Cafe1

E
D

data label
IP address
Flow Control or Decision (Cont.)

Switch Statement (Example)

switch Label Variable


case 4 Assigned Value1
display ('Route to Interface Out_interface 1‘) Statement 1
display ('Label 9') Statement 2
case 1 Assigned Value2
display ('Route to Interface Out_interface 2‘) Statement 3
dispaly ('Label 5') Statement 4
otherwise
display ('No Route') Statement 5
end
Flow Control or Decision (Cont.)

Switch Statement (Example)

Cocacola 1
Max 2
VeVe 3
Red Bull 4
Sprite 5
7 Up 6
Asia 7
Flow Control or Decision (Cont.)

Switch Statement

switch Variable
case {Assigned Vale1, Assigned Value2, Assigned Value3,…}
Statement 1
case {Assigned Vale4, Assigned Value5, Assigned Value6,…}
Statement 2
otherwise
Statement 3
end
Flow Control or Decision (Cont.)

Switch Statement (Example)

BST-A
BST BSC1
BST-B
BST-C BSC1

BST-D
BST-E
BST-F
BST-G
BST-H BSC2

BST-I
BST-J
Flow Control or Decision (Cont.)

Switch Statement (Example)

clc
clear
BST=input('Enter Base Station No. \n','s');
switch BST Variable
case {'A','B','C','D','E'} Assigned Values
display('It is controlled by BSC-1') Statement 1
case{'F','G','H','I','J'} Assigned Values
display('It is controlled by BSC-2') Statement 2
otherwise
display ('No controlled by BSC-1 or BSC-2') Statement 3

end
Flow Control or Decision (Cont.)

Switch Statement (Example)

Mon 7, 14, 21, 28


Tue 1, 8, 15, 22, 29
Wed 2, 9, 16, 23, 30
Thu 3, 10, 17, 24
Fri 4, 11, 18, 25
Sat 5, 12, 19, 26
Sat 6, 13, 20, 27
Looping with For (Cont.)

For Loop

“for loop” is used for repeating actions for a certain number of times
given in a program. The structure of for loop is as follows.

for Variable=Expression

Statement 1 The “Statement 1, Statement 2,… ”


will be performed for a certain
Statement 2
times defined in the expression.

end
Looping with For (Cont.)

For Loop (Example)

Variables
1st round k=1
for k=1:1:10 Expression P(1)=2*1

P(k) = 2*k Statement 2nd round k=2


P(2)=2*2
end
3rd round k=3
P(3)=2*3

10th round k=10


P(10)=2*10
Looping with For (Cont.)

For Loop (Example)

Write a program to calculate the total sum of given first number


and last number.

Total=first+(first+1)+(first+2)+…+(last-2)+(last-1)+last

e.g.,

first number=1

last number=5
Total=1+2+3+4+5=15
Looping with For (Cont.)

For Loop (Example)

clc

Variables clear
FN=input('Enter first number \n');
for Num=FN:FL Expression FL=input('Enter last number \n');
Sum=0;
Total=Sum+Num; Statement1
for Num=FN:FL

Sum=Total; Statement2 Total=Sum+Num;


Sum=Total;
end end
display(Total)
Looping with For (Cont.)

For Loop (Example)

clc 1st round Sum=0 , Num=1


Total=1
clear
Sum=Total =1
FN=input('Enter first number \n');
FL=input('Enter last number \n'); 2nd round Sum=1, Num =2
Total=3
Sum=0;
Sum=Total=3
for Num=FN:FL ...
Total=Sum+Num; ...
Sum=Total; ...
5th round Sum=10, Num =5
end
Total=15
display(Total) Sum=Total=15
Looping with For (Cont.)

For Loop (Example)

Write a program that works like a cash register. Use


a sample of products given in the following table.
Product code must be input by the user in this
example.

Product code Item Name Price

40200 Book 500


81007 Pen 350
Cash register
90660 Pencil 150
53111 Correction Pen 650
Looping with For (Cont.)

For Loop (Example)

clc
Variables clear
Code=[40200, 81007, 90660, 53111];
for k=1:n Name={'Book','Pen','Pencil','Correction Pen'};
Price=[500 350 150 650];
if PD==Code(k) PD=input ('Enter Product Code \n');
n=length(Code);
Item=Name{k}; for k=1:n
if PD==Code(k)
Cost=Price(k); Item=Name{k};
Cost=Price(k);
end
end
end
end
Item
Cost
Looping with For (Cont.)

Switch Statement and For Loop

switch PD
Code
case {40200, 81007, 90660, 53111}
Statement 1 ??????????
end

for k=1:n
if PD==Code(k)
Item=Name{k};
Cost=Price(k);
end
end
Looping with For (Cont.)

For Loop (Example)

y
6m

x
2 kN

Write a program to calculate shear force and bending


moment at different locations x=0 m; 0.5 m, 1 m , 1.5
m, 2 m, 2.5 m, 3 m, 3.5 m, 4 m, 4.5 m, 5 m, 5.5 m, 6 m.
Fy=Fs-2000=0
M=M+(6-x)*2000=0
Looping with For (Cont.)

For Loop (Example)

clc
clear
for k=1:n; x=[0:0.5:6];
n=length(x);
Fs(k)=-2000; for k=1:n;
Fs(k)=-2000;
M(k)=-(6-x(k))*2000; M(k)=-(6-x(k))*2000;
end
end Fs
M
Looping with For (Cont.)

For Loop (Example)

Write a MATLAB program to predict classification of a new product


based on survey data by using knn algorithm. The survey data are given below
and query instance (features of new product) is (3,7).

X Y Classification
7 7 Bad
7 4 Bad
3 4 Good
1 4 Good
Looping with For (Cont.)

For Loop (Example)

Write a MATLAB program to predict the value of y for a query


instance x=2.5 by using knn algorithm. Use k=3. Then, try with simple
weighted knn method.
x y
w1=a; w2=a/2; w3=a/3;…, wk=a/k 1 2.3
2 4.5
w1=a; w2=a/2; w3=a/4;…., wk=w/(2k) 3 6.1
4 8.0
5 11.3
w1=a; w2=a/(y1near-y2near);
6 10.9
w3=a/(y1near-y3near);;…., wk=w/(y1near-yknear); 7 12.3
8 15.5
9 18.0
w1+w2+w3+…wk=1 10 20.2
Looping with For (Cont.)

Nested For Loop

“Nested for loop” is applicable to repeat actions in multi


dimensional looping. The general form of “Nested for loop” is as
follows.

for Variable1=Expression1 Statement 1 in outer loop will be


Statement 1 performed for a certain times
for Variable2=Expression2 defined in the Expression1.

Statement 2
Statement 2 in inner loop will be
… performed for a certain times
end defined in the Expression2 at every
end loop of Expression1.
Looping with For (Cont.)

Nested For Loop (Example)

Write a function M-file that can show index of the maximum


element in a two dimensional matrix. The matrix name should be the argument
and the function name should be indmaxele.

>> [Row, Column]=indmaxele (A)


 1 0 2 Row=
A   5  1 6 3
11 9 3 Column=
1
Looping with For (Cont.)

Nested For Loop (Example)

function [Row,Column] = indmaxele(A)


[m,n]=size(A);
maxele=A(1,1);
for r=1:m; Outer for loop
for c=1:n; Inner for loop
if A(r,c)> maxele
maxele=A(r,c); if statement A(1,1) A(1,2) A(1,3)
Row=r;
Column=c;
A(2,1) A(2,2) A(2,3)
end
end
A(3,1) A(3,2) A(3,3)
end
end
Looping with For (Cont.)

Nested For Loop (Example)

Write a MATLAB program to find the location of elements


1 in a given matrix.

0 0 0 0 0
0 0 1 0 0
 
A  0 0 0 1 0
 
0 0 0 1 0
0 0 1 0 0
Looping with For (Cont.)

Nested For Loop (Example)

clc
clear
A=input('The matrix A \n');
[row, col]=size(A);
k=0;
for m=1:row Outer for loop
for n=1:col Inner for loop
if A(m,n)==1;
k=k+1;
Locx(k)=m; if statement
Locy(k)=n;
end
end Outer for loop end
end Inner for loop end
Locx
Locy
Looping with For (Cont.)

Nested For Loop (Example)

Create a MATLAB function to reorder the elements in a given matrix


in ascending order. Don’t use MATLAB built-in function “sort” or “sortrows”.

Example Before After


-1 -1
3 0
2 2
0 3
11 4
6 6
4 11
Looping with For (Cont.)

Nested For Loop (Example)

Develop an image processing algorithm that can detect the ripeness


of a banana by differentiating its skin color.

Example
Looping with For (Cont.)

Nested For Loop (Example)

Develop an image processing algorithm that can detect the regions in


an image.
Looping with For (Cont.)

Nested For Loop (Example)

Develop a MATLAB function that works like the function


“rangefilt” (range function).
Looping with For (Cont.)

Nested For Loop (Example)

Move at every 3 minutes.


Whenever it moves, it moves
three points.
Vertical and horizontal
movement is alternative.
Moving up or down and left or
right is random.
Looping with While (Cont.)

While Loop

“While Loop” is used to repeat the actions in the loop as long


as the given condition is true. The general format of “While Loop” is
as follows.

while Condition As long as the Condition is correct,


Statement 1 the program will work on
Statement 2 Statement 1, Statement 2. When
… Condition is not correct, the wile
end loop will end.
Looping with While (Cont.)

While Loop (Example)

Write a program to calculate how long it will take to attain the


total balance more than 50000 started from a saving amount of 10000
with an interest rate of 10% per year as follows.

Total Balance=Save(1+0.1)
Looping with While (Cont.)

While Loop (Example)

Condition clc
clear
Year=0;
while Total_Balance<=50000
Total_Balance=10000;
Year=Year+1; Save=10000;

Total_Balance=Save*(1+0.1); while Total_Balance<=50000


Year=Year+1;
Save=Total_Balance;
Total_Balance=Save*(1+0.1);
end Save=Total_Balance;
end
Year
Looping with While (Cont.)

While Loop (Example)

Write a program to calculate the solution of a quadratic


equation by using Newton’s iteration method. The input should be the
coefficients of the quadratic equation and the acceptable convergence
tolerance is 0.001.

f ( x0 )
ax 2  bx  c  0 x1  x 0  '
f ( x0 )
f ( xn ) f ( x1 )
x n 1  x n  x 2  x1  '
f ' ( xn ) f ( x1 )

Initiate or Guess=x0 Convergence tolerance=x2-x1<0.001


Looping with While (Cont.)

While Loop (Example)

clc
clear
Coe=input('Enter the coefficient matrix \n');
x=input('Enter the initially guessed value \n');
Conv_error=1;
Condition
Num_itr=0;
while Conv_error>0.001;

Statements
xn=x-[Coe(1)*x^2+Coe(2)*x+Coe(3)]/[Coe(1)*2*x+Coe(2)];
Conv_error=abs(xn-x);
x=xn;
Num_itr=Num_itr+1;
end
x
Num_itr
Looping with While (Cont.)

While Loop (Example)

 
100 m

 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 1 0

 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
100 m 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
Looping with While (Cont.)

While Loop (Example)

clc
clear
Region=zeros(20);
n=5;
for k=1:n;
lop=1;
Condition
while lop==1
x=randi(20);
y=randi(20);
if Region(x,y)==1;
lop=1;
Statements in while loop
else
lop=2;
end
end While loop end
Region(x,y)=1;
end
Region
Looping with While (Cont.)

While Loop (Example)

[1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 0]
Looping with While (Cont.)

While Loop (Example)

Design 2

Design 1
Looping with While (Cont.)

While Loop (Example)

Motors Control unit


13

Parking
Info Park
Leave

Password
1 25

[0 444668 0 678902 55511 0 40111….]


Looping with While (Cont.)

While Loop (Example)

clc
clear
Go=1;
Series=zeros(1,25);
n=25;
while Go==1;
Sig=input('1 if Park or 0 if Leave\n\n');
if Sig==1
Password=input('Enter your password \n');
Password1=input('Confirm your password \n');
while Password~=Password1
display ('Wrong Confirmation')
Password1=input('Reenter your password\n');
end
Series(1)=Password;
end
if all(Series~=0);
Go=0;
end
end
Breaking a Loop

Break Command

for Variable = Expression while Condition1


Statement 1 Statement 1
Statement 2 Statement 2
if Condition if Condition2
break break
end end
end end

If the Condition in if statement is correct, the loop will stop


although the loop still needs to continue more.
Breaking a Loop (Cont.)

Break Command (Example)

Write a program to calculate addition of 2 for twenty times.

Total= 2+ 2+ 2+ 2+……..2

20
Breaking a Loop (Cont.)

Break Command (Example)

clc
clear
Total=0;
k=0;
for i=1:1000; 1:1000

k=k+1;
Total=Total+2;
if k==20;
break Break command
end
end
Breaking a Loop (Cont.)

Break Command (Example)

Write a program to calculate the solution of a quadratic


equation by using Newton’s iteration method. The input should be the
coefficients of the quadratic equation and the acceptable convergence
tolerance is 0.001. Use break command in the program.

f ( x0 )
ax 2  bx  c  0 x1  x 0  '
f ( x0 )
f ( xn ) f ( x1 )
x n 1  x n  x 2  x1  '
f ' ( xn ) f ( x1 )

Initiate or Guess=x0 Convergence tolerance=x2-x1<0.001


Breaking a Loop (Cont.)

Break Command (Example)

Write a program that suddenly break the loop of escalator when it is


overloaded or the user switch off.

Maximum load is random

The allowable maximum load =3 tons


Continuing a Loop

Continue Command

for Variable = Expression


Statement 1
if (Condition) If the Condition in if statement is
continue correct, the loop will start next loop
end without working on Statement 2.
Statement 2
end
Continuing a Loop (Cont.)

Continue Command

Write a program to count the number of odd number in a


given vector.

A=[4 5 6 6 8 9 1 0 3 6 4 9]
Continuing a Loop (Cont.)

Continue Command

clc
clear
A=input ('Enter the vector \n');
n=length(A);
Count=0;
for k=1:n;
if rem(A(k),2)==0
continue Continue command
end
Count=Count+1;
end
Continuing a Loop (Cont.)

Continue Command (Example)

Write a MATLAB program that works like an

elevator.
Pausing a Loop

Pause Command

for Variable = Expression


At every run the program will work
Statement 1
on Statement 1 and Statement 2.
Statement 2
The the loop will be paused until
pause the user press any key.

end
Pausing a Loop

Pause Command (Example)

clc

clear

for k=1:5;

display ('Hi, What is your name?') Pause


command
pause

end
Components of a Program

Start

Input or Assigning

Working Statement

Output or Displaying
?
End
Displaying Messages and Results

Simple Display

disp (‘Message’)

disp (Variable)

display (‘Message’)

display (Variable)

e.g.,

>>Y=[2 5; 6 7]; >>disp(X)

>>X=[ ]; >>display(Y)

>>disp(Y) >>display(X)
Displaying Messages and Results (Cont.)

Error and Warning

error (‘Message’) The program will stop working.

warning (‘Message’) The program will be still working.

e.g.,
error (‘It is not a positive number)
warning (‘It is not a positive number)
Displaying Messages and Results (Cont.)

Example

clc
clear
x=input('Enter a positive integer \n');
if x<0
error('It is not a positive integer'); Error Message
end
Y=x^2;
display(Y)
Displaying Messages and Results (Cont.)

Example

clc
clear
x=input('Enter a positive integer \n');
if x<0
warning('It is not a positive integer‘) Error Message
end
Y=x^2;
display(Y)
Displaying Messages and Results (Cont.)

sprintf
Flag

Character type

Format start
%+12.5f
(Precision)
Decimal places
Total Width

e.g.,
>>X=pi;
>> sprintf(‘%+12.5f',X) +3.14159
Displaying Messages and Results (Cont.)

Flag Option

Flag Explanation Example

To mention + and – signs before


+ +3,-4.26
the number

To mention + and – signs before


- 3,-4.26
the number if necessary

To mention 0 if there are extra


0 03,-004.26
space before the number
Displaying Messages and Results (Cont.)

Character Option in sprintf

Flag Explanation Example

c To print single character 2, A

d To print integers +308, -10, 111

e To print data in scientific notation 3.1415e+00

E To print data in scientific notation 3.1415E+00

f To print in decimal notation 4.653, -0.256


To print in scientific notation or
g
decimal notation (suitable one)
Displaying Messages and Results (Cont.)

Character Option in sprintf

Flag Explanation Example

To print in scientific notation or


G
decimal notation (suitable one)

s To print string of character Hello

To print in decimal notation but +


or – sign before number is
u 308, -10 , 111
mentioned suitably although the
flag is declared.

*** Cannot do any further calculation after using sprintf


Displaying Messages and Results (Cont.)

fprintf
Flag

Character type

Format start
%+12.5f\n
(Precision)
Decimal places
Total Width

e.g.,
>>X=pi;
>>fprintf(%+12.5f) +3.14159
Saving to External Files

Writing to Excel File

xlswrite(‘Filename’, Variable, Sheet no, ‘Range’)

xlswrite(‘Mydata’, X, 4, ‘A1:E5’)

e.g.,

>> X=1:100;
>> xlswrite(‘Mydata’, X, 4, ‘A1:E5’)
Saving to External Files

Writing to Text or Word File

Function to create a new file


File identifier
File name

fid=fopen(‘filename’, ‘Mode’)
Permission
mode

fprintf(fid, ‘format’, Variables)

File identifier Variables to


Printing be printed
format
Saving to External Files

Writing to Text or Word File (Example)

>> x=0:0.1:1;

>> y= exp(x);

>> c=[x ; y]; Write mode

>> fid=fopen(‘exp.txt’, ‘w’)

>> fprintf(fid, ‘%f %f \n’, c)

>>fclose(fid)
Writing format
Saving to External Files

File Mode Options

File
Explanation
Mode
r To set the file in reading mode

w To set the file in writing mode (discard the existing data)


a To set the file in writing mode (add data to existing data )
r+ To set the file in reading and writing mode

w+ To set the file in reading and writing mode (discard the existing data)

a+ To set the file in reading writing mode (add data to existing data )
Saving to External Files

File Mode Options (Example)

xxxxx
>> X=1:10; xxxxx
xxxxx Exiting data
>> fid=fopen(‘exp.txt',’a'); xxxxx
xxxxx
>> fprintf(fid,'%f %f\n',X); xxxxx
xxxxx
xxxxx New data
>> type ‘exp.txt’ xxxxx
xxxxx
>> A=load(‘exp.txt‘) xxxxx
Saving to External Files

File Mode Options (Example)

>>X=[1:10]; Read mode

>>fid=fopen('exp1.txt','r');

>>fprintf(fid,'%f %f\n',X);

Error using fprintf Invalid file identifier. Use fopen to

generate a valid file identifier.


Saving to External Files

File Mode Options (Example)

>>X=[1:10]; Read mode

>>fid=fopen(‘exp.txt','r');

>>A=fscanf(fid,'%f‘)

A=fscanf(file identifer,‘format’)

A=fscanf(file identifer,‘format’, size)


Saving to External Files

File Mode Options

A=fscanf(file identifier, ‘format’)

A=fscanf(file identifier, ‘format’, size)

inf Read to the end of the file. (default)


N Read at most N elements into a column vector.
[M,N] Read at most M * N elements filling at least an M-by-N
matrix in column order. N can be inf, but M cannot.
Saving to External Files

File Mode Options

Write only

>> X=[1:10];
>>fid=fopen('exp2.txt','w');
Moving
>>fprintf(fid,'%f\n',X);
cursor to the
>>frewind(fid); beginning
>>fscanf(fid,'%f') Not
applicable
ans =
[]
Saving to External Files

File Mode Options


Read and write

>>X=[1:10];
>>fid=fopen('exp2.txt','w+');
>>fprintf(fid,'%f\n',X);
>>frewind(fid); Reset the
curser
>>A=fscanf(fid,'%f')
>>frewind(fid); Reset the
curser
>>A=fscanf(fid,'%f',[2,5])
Input/Output Related Functions

Flag Explanation Example

>>menu(‘Choice
menu Generate a menu for choices ’, ‘Red’, ‘Blue’,
‘Green’)
To see the output in sequence in
more >> more on
command window.
diary Save the command window >>diary
Convert integers from 0 to 65535
char where 0-127 correspond to 7-bit >> char(50)
ASCII code.
Covert to numeric value with double
double >>double (‘Mg’)
precision
Input/Output Related Functions

Flag Explanation Example

Covert to numeric value with single


single >>single(‘Mg’)
precision

num2str Convert number to string >>num2str(5)

Rounds the elements of the matrix


int2str X to integers and converts the result >>int2str(78.1)
into a string matrix.
Execute string with MATLAB
eval >>eval(‘2*2+5’)
expression.
Checking Error and Debugging

Syntax Error

Missing parenthesis
>> 4*(2+5
??? 4*(2+5
|
Error: Expression or statement is incorrect—possibly unbalanced (, {, or [.

Missing operator
??? 4 (2+5)
|
Error: Unbalanced or misused parentheses or brackets.
Checking Error and Debugging

Syntax Error

Misspelled variable name


>> 2x=4*(2+5)
??? 2x=4*(2+5)
|
Error: Unexpected MATLAB expression.

Wrong Spelling
>> srqt(25)
??? Undefined command/function 'srqt'.
Checking Error and Debugging

Other General Error

xxxxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxx
??? Error: File: Test10.m Line: 6 Column: 9
xxxxx
xxxxxxxxx Unexpected MATLAB operator.

xxxxxxxxxxxx
xxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxx
Checking Error and Debugging

Setting Breakpoint and Return Command

clc
clear
b=input('Enter the Base of the Triangle (m) \n');
h=input('Enter the Height of the Triangle (m) \n')

 format bank
Area=0.5*b*h ;
display (['Area =', num2str(Area), ' Square Meter'])
save Area

K>> return
Checking Error and Debugging

Setting Breakpoint and Return Command

clc
clear
b=input('Enter the Base of the Triangle (m) \n');
h=input('Enter the Height of the Triangle (m) \n')
With condition
e.g., h==3  format bank
Area=0.5*b*h ;
display (['Area =', num2str(Area), ' Square Meter'])
save Area

K>> return
Checking Error and Debugging

Error Handling

There will be debugging option


if there is error.

There will be debugging option


if there is warning.
Chapter End Exercise

1. Write function M-files that enable multiplication of element by element from

two vectors or matrices if they have the same number of elements.

2. Write a list of student names and their corresponding marks in random

arrangement. Develop a scrip M-file to read that file and rearrange the student

names and their marks in descending order and rewrite in a new excel file.

Please don’t use MATLAB built-in functions, sortrows and sort function.
Chapter End Exercise

3. Write a MATLAB program to print the following table in command window.

Number Price per


No. Item Name Total cost
of Items Item
1 Book 3 500 1500

2 Pencil 3 100 300

3 Pen 2 200 400

4 Sharpener 1 250 250

5 Eraser 1 300 300


Chapter End Exercise

4. Write a MATLAB program to distribute a group of sensors in an area. After

distribution, each sensor node must be able to detect and list the partners in

its convergence region.

C
F B D
E
G
Chapter 4

Plotting Graphs
&
Curve Fitting Toolbox
Chapter Objectives

■ To get familiar with MATLAB plotting functions by answering the


following questions,
What are possible ways to create graphs in MATLAB?
What are the advantages and disadvantages of using toolbox and
command lines?
What are the main features of a graph?
What are the special graphs used in engineering subjects?

■ To practice on MATLAB plotting function related to engineering


applications.
Two Ways for Creating Graphs

1. By using plotting tool (toolbox)

2. By using command lines

Way 1 Way 2

Easier and more convenient More difficult and not


to use convenient to use

Cannot be integrated in M- Very useful to be integrated in


files M-files
Plot Menu
Variable Plot type
Plot Functions in M-Files

M-File

xxxxxxx
xxxxxx
xxxxxx
xxxxx
xxxxxxx
xxxx Y
xxxxxx
xxxxxx
xxxxxxx
plot(x,y) Plotting
graph

X
Plot Functions in GUI

M-File

xxxxxxx
xxxxxx
xxxxxx
xxxxx
xxxxxxx
xxxx
xxxxxx
xxxxxx
xxxxxxx
plot(x,y) Plotting
graph
Components of a Graph

Figure name Menu bar Tool bar Dock / Undock

Legend
Line plot

Axis label

Y-axis Grid line

X-axis
Creating 2D Line Graphs

Line Graph

It is used to show continuous data progress, for examples, the increase &
decrease of data with respect to other parameter and to draw some geometries in
the figures.
Creating 2D Line Graphs (Cont.)

Line Graph

Some applications
Creating 2D Line Graphs (Cont.)

Plot

Function Explanation

plot (Y) Plot the elements in Y vector by setting their


corresponding indices on x-axis

plot (X,Y) Plot the elements in X vector vs. the elements in Y


vector

e.g., >>X= [ 1 2 3 4 5 6 7 8 9 10 ]
>>Y= [30 28 29.5 31 30 30 28 29 31 32]
>> plot(Y)
>> plot (X,Y)
Creating 2D Line Graphs (Cont.)

Plot

>> X= [0 : pi/100 : 2*pi];


Sin(X)
>> Y= sin (X);

>> Y1= cos (X); Cos(X)

>> plot (X,Y,X,Y1)


Creating 2D Line Graphs (Cont.)

Line Specifications

Variables Line Specifications

plot(X,Y, 'line color marker shape line style', 'LineWidth', 2,

'MarkerSize', 14 , 'MarkerFaceColor', 'k', 'MarkerEdgeColor', 'g')

e.g.,

plot(X,Y, 'bo-', 'LineWidth', 2,

'MarkerSize', 14 , 'MarkerFaceColor', 'k', 'MarkerEdgeColor', 'g')


Creating 2D Line Graphs (Cont.)

Line Specifications

b - Blue color

- - Solid line

o - Circle shape marker

'LineWdith' - to define the width of the line

'Markersize' - to define the size of marker

'MarkerFaceColor' - to define the color of marker face

'MarkerEdgeColor ' - to define the color of marker edge


Creating 2D Line Graphs (Cont.)

Line Specifications

Name Line Style Symbols

_____________
Solid line -
_
………………
Dotted line .


Dashed line --

.  .  .  .  .
Dash-Dot line -.
.
Creating 2D Line Graphs (Cont.)

Line Specifications

Color Symbol Physical nature


Cyan c ___
Magenta m ___
Yellow y ___
Red r ___
Green g ___
Blue b ___
White w ___
Black k ___
Creating 2D Line Graphs (Cont.)

Line Specifications

Marker shape Symbol Marker shape Symbol

. .  ^
o o  >
 x  <
+ +  p
* *  h
□ s
◊ d
 v
Creating 2D Line Graphs (Cont.)

Line Specifications (Example)

Day 1 2 3 4 5 6 7 8 9 10

Temperature 30 28 30 31 30 30 28 29 31 32

>> X= [ 1 2 3 4 5 6 7 8 9 10 ];

>> Y= [30 28 30 31 30 30 28 29 31 32];

>> plot (X,Y, ': s k', 'LineWidth', 2.5 ,'MarkerSize', 10, 'MarkerFaceColor','g',

'MarkerEdgeColor','r' )
Creating 2D Line Graphs (Cont.)

Line Specifications (Example)

Simulate common traffic pattern (arrival) to a base station


in a office day by using Poisson distribution function.

p ( t, ) T  [ t1 t 2 t 3. ...t 24 ]
 (t ) 
maxp ([ T ],  )

 t 
p (t ,  )  e
t!
Editing Axes

Limits

X-limits Y-limits

axis ([ Xmin Xmax Ymin Ymax ])

Function Explanation
axis equal To obtain equal tick mark intervals
axis square To obtain equal length of axes

To obtain the axes limits the same as


axis tight
maximum and minimum of data

axis normal To set the axes as normal


Editing Axes (Cont.)

Limits

Function Explanation
To obtain equal tick mark intervals but the
axes limits the same as maximum and
axis image
minimum of data.

axis auto To automatically adjust the axes

axis on To see the axes

axis off To hidden the axes


Editing Axes (Cont.)

Limits (Example)

Write a function M-file to draw a circle with an arbitrary radius . See the
results by changing the axis styles.

>> circle (100)


Editing Axes (Cont.)

Limits (Example)
No output

function [ ]=circle(R);
Ang=0:0.05:2*pi;
X=R*cos(Ang);
Y=R*sin(Ang);
plot(X,Y,'LineWidth',2) No output

axis equal Axis style


end
Editing Axes (Cont.)

Graph Title, Axis Labels, Texts

xlabel(‘X value’)
Multiple
labels
xlabel({date;'Population';'in Years'})

ylabel(‘Y value’)

text(x,y, ‘Value’)

Location in the graph


Editing Axes (Cont.)

Graph Title, Axis Labels, Texts

title ( 'text.............','FontSize', 12, 'FontName', 'TimesNewRoman',


'FontAngle', 'Italic','FontWeight','Bold')

xlabel ( 'text.............','FontSize', 12, 'FontName', 'TimesNewRoman',


'FontAngle', 'Italic','FontWeight','Bold')

ylabel ( 'text.............','FontSize', 12, 'FontName', 'TimesNewRoman',


'FontAngle', 'Italic','FontWeight','Bold')

Text (x,y, 'text......', 'FontSize', 12 ,'FontName', 'TimesNewRoman',


'FontAngle', 'Italic','FontWeight','Bold')
Editing Axes (Cont.)

Graph Title, Axis Labels, Texts

Specification Explanation Options

Fontsize To define font size

FontName To define font

FontAngle To define font style Normal, Italic or Oblique

Light, Normal, Demi,


FontWeight To define font weight
Bold
Color To define font ‘g’, ‘k’, ‘r’, ‘b’, ‘c’, ‘y’
Editing Axes (Cont.)

Greek Letter in Title and Axes

Character Symbol Character Symbol


\alpha α \versigma ϑ
\angle  \kappa κ
\ast * \lambda λ
\beta  \mu µ
\gamma  \nu ν
\delta  \pi π
\epsilon  \rho ρ
\zeta  \sigma σ
\eta  \tau τ
\theta  \equiv 
Editing Axes (Cont.)

Greek Letter in Title and Axes (Example)

  

xlabel (‘0 \leq X \leq 2 \pi’)

xlabel ('0 \leq X \leq 2 \pi', 'FontSize',14, 'FontAngle','Italic', 'FontName',


'TimesNewRoman')
Editing Axes (Cont.)

Font Modifiers

\bf Bold font

\it Italic font

\sl Oblique font

\rm Normal font

xlabel (‘\bf 0 \leq X \leq 2 \pi', 'FontSize',14, 'FontAngle','Italic',


'FontName', 'TimesNewRoman')
Editing Axes (Cont.)

Tick Location and Tick Label


Where to locate

set (gca,'Xtick', tick-mark location) Assign label

set(gca,'XTickLabel',{'tick-mark label'}, 'FontSize',12,

'FontName', 'TimesNewRoman')

set (gca,'Ytick', tick-mark location)

set (gca,'YtickLabel', {'tick-mark label'})


Editing Figures

Adding Legend

legend(‘toggle’)

legend(‘data1’, ‘data2’)

legend(‘data1’, ‘data2’, ‘Location’, ‘______’, ‘Orientation’,

‘________’)

legend(‘data1’, ‘data2’, ‘Location’, ‘NorthEast’, ‘Orientation’, ‘Vertical’)


Editing Figures (Cont.)

Adding Legend Position Options

Options

North NorthOutside NothEast NothEastOutside Best

South SouthOutside SouthEast SouthEastOutside BestOutside

East EastOutside NorthWest NorthWestOutside

West WestOutside SouthWest SouthWestOutside


Editing Figures (Cont.)

Adding Legend Orientation Options

Options

Vertical Horizontal

>> legend off


>> legend show
>> legend boxoff
>> legend boxon
Editing Figures (Cont.)

Adding Color Bar

>> colorbar

Color Bar Position Options

North NorthOutside

South SouthOutside

East EastOutside

West WestOutside
Editing Figures (Cont.)

Adding Plots to an Existing Graph

>> hold on

Example

>> X= [0 : pi/20 : 2*pi];


>> Y=sin(X);
>> Y1=cos(X);
>> plot(X,Y)
>> hold on
>> plot(X,Y1)
Editing Figures (Cont.)

Adding Grid Lines to Graph

>> grid on
>> grid off
Example

>> X=[0:pi/20:2*pi];
>> Y=tan(X);
>> plot (X,Y)
>> grid on
>> grid off
Editing Figures (Cont.)

Specifying View Point on Graph

Z >> x=1:100;
Y
>> y=sin(x);
>> plot(x,y)
Elevation
>> view(3)
X
>> view(2)
>> view(-45,40)
Y Azimuth >> view ([-2,10,24])

Azimuth = -37.5º, Elevation = 30º


Plotting Tool

Plot type

Data to plot
Plotting Tool (Cont.)
Special Graphs

Bar Graph

It is used to show discrete data progress, for examples, the increase & decrease
of data happened in a period, increase & decrease happened with respect to
different kinds of parameters.

Network growth Normalized energy consumption and traffic for


different loads
Special Graphs (Cont.)

Bar Graph
Some applications

Growth in Base Stations in Developing in Developing Region 2007-2012 (GSMA,2010)


Special Graphs (Cont.)

Bar Graph

bar (X,Y)
e.g.,
bar (X,Y, ‘stack’)
barh(X,Y) >> X=1999 : 2003;
bar (X,Y, ‘stack’) >> Y=[5 2 1; 8 7 3; 9 8 6; 5 5 5; 4 3 2];
bar3(X,Y) >> bar3(X,Y,'group')
bar3(X,Y, ‘stack’) >>bar3(X,Y,'stack')
bar3h(X,Y)
bar3h(X,Y, ‘stack’)
Special Graphs (Cont.)

Area Graph

It is used to show data progress, for examples, the increase & decrease of data
happened in a period. It has similar nature as bar stacked graph.
Special Graphs (Cont.)

Area Graph
Some applications
Special Graphs (Cont.)

Area Graph

area(X,Y)
e.g.,

area(X,Y, level)
>> X=1999 : 2003;
>> Y=[5 2 1; 8 7 3; 9 8 6; 5 5 5; 4 3 2];
>> area (X,Y)
>> set(gca,'Xtick',1999:2003)
Special Graphs (Cont.)

Pie Chart

It is used to show the percentage of contribution of each type in a


group.
Special Graphs (Cont.)

Pie Chart
Some applications
Special Graphs (Cont.)

Pie Chart

>> pie(Variable);

>> pie(Variable,{‘Streing1’,‘String2’,…})

>> pie(Variable, [0 0 1], {‘Streing1’,‘String2’,…} )

>> pie3(Variable)

>> pie3(Variable, [0 0 1], {‘Streing1’,‘String2’,…} )


e.g.,

>>Product=[1500 2300 1800];

>> pie(Product);
Special Graphs (Cont.)

Histogram

It is mostly used in quality control in manufacturing. It is also used in image


processing.

Frequency

Intensity
Special Graphs (Cont.)

Histogram

>> hist (X)

>> hist(X,20)

>> hist(Y,X)
e.g.,
>> dimension = [1.4 1.4 1.5 1.5 1.5 1.6 1.5 1.4 1.6 1.4 1.3
1.6 1.5 1.5 1.5 1.4 1.5 1.5 1.3 1.5];
>> hist(dimension)
>> hist(dimension,20)
>>hist(dimension,[1.3 1.4 1.5 1.6])
Special Graphs (Cont.)

Polar Histogram

>> rose (X)

>> rose(X,N)

>> rose(Y,X)
e.g.,
>> Angles=[pi, pi/2, pi/2, 3/2 *pi, 3/2 *pi, 3/2 *pi, 3 /2 *pi];
>> rose(Angles)
>> rose(Angles,500)
>>rose(Angles,[pi, pi/2, 3*pi/2]
Special Graphs (Cont.)

Stem Graph

It is used in electrical engineering to show electrical signal pulse from a


base line and to show residual amount (difference) of two data lines.
Special Graphs (Cont.)

Stem Graph

e.g.,
>>stem(Y)
>> Y=sin([2 5 6 7 9 0 1 -2 -3]);
>>stem(X,Y)
>> stem(Y)
>>stem(x,y,'--sr','fill')
>> x=0:pi/20:2*pi;

>> y=sin(x);

>> stem(x,y)

>> stem(x,y,'--sr','fill')
Special Graphs (Cont.)

Stairstep Graph

The application stairstep graphs are mostly found in digital signal


processing.

Amount

1
0

time
Special Graphs (Cont.)

Stairstep Graph

Some application
Special Graphs (Cont.)

Stairstep Graph

>> stairs(Y) e.g.,

>>stairs(X,Y)
>> t=1:10;

>> y=cos(t);

>> stairs(t,y)
Special Graphs (Cont.)

Compass Graph and Feather Graph

Compass graphs is used to show the magnitude and direction in polar


coordinates system.
Special Graphs (Cont.)

Compass Graph and Feather Graph

>> compass(Y) e.g.,

>> compass(X,Y) >> Dir=[40 100 120 65 180 360


270 335 335];
>> Winds=[6 8 6 3 9 6 10 14 12];
>>Rdir= pi/180* Dir;
>>[x,y]=pol2cart (Rdir,Winds);
>> compass(x,y)
>> feather(x,y)
Special Graphs (Cont.)

Contour Graph

Contour graphs are used to demonstrate the magnitude that changes


with respect to both X and Y.
Special Graphs (Cont.)

Contour Graph

>>contour(X)

>> contour(X, 20) e.g.,


>> colorbar
Temp=[0 0 0 0 0;
>> h=contour(X,9);
>> clabel(h) 0 21.4 38.4 57.1 100;
0 47.3 75 90.2 100;
>> contourf(Temp1, 20)
0 92.8 124.1 128.57 100;
>> contour3(Temp1,20) 200 200 200 200 200]
Special Graphs (Cont.)

Mesh & Surf Graph

>> mesh(X)
e.g.,
>>meshc(X)
Temp=[0 0 0 0 0;
>>surf(X)
0 21.4 38.4 57.1 100;
>>surfc(X) 0 47.3 75 90.2 100;
0 92.8 124.1 128.57 100;
200 200 200 200 200]
Special Graphs (Cont.)

Errobar Graph

This type of graphs are used to show data with uncertainness. Thus,
each data point in the graph has lower and upper limits.
Special Graphs (Cont.)

Errobar Graph

errorbar(X,Y,E)
>> Location=[0 2 4 6 8 10 ];
errorbar(X,Y,LE,UE)
>> MeasureT=[690 524 357 190 79 54 ];

>> Error=[5 5 5 5 5 5 ];
e.g.,
>> errorbar(Location, MeasureT, Error)

>> Eu=[5 5 5 5 5 5 ];

>> El=[3 3 3 3 3 3];

>>errorbar(Location, MeasureT, Eu, El)


Special Graphs (Cont.)

Logarithmic Graphs

This type of graphs are used to show data that changes in log scale.
Special Graphs (Cont.)

Logarithmic Graphs
Some applications
Special Graphs (Cont.)

Logarithmic Graphs

>> loglog(X,Y)
e.g.,
>>semilogx(X,Y)
>> x=0.1:0.01:100;
>>semilogy(X,Y)
>> y=exp(x);
>> loglog(x,y,'LineWidth',2.5)
>> semilogx(x,y)
>> semilogy(x,y)
>> grid on
Special Graphs (Cont.)

Graphs with Two Y Axes


Special Graphs (Cont.)

Graphs with Two Y Axes


Some applications
Special Graphs (Cont.)

Graphs with Two Y Axes

>> plotyy (X,Y,X,Y1)

>> X=[1: 2:100]

>> Y=sin(X);

>> Y1=2*X+2;

>> plotyy (X,Y,X,Y1)


Drawing Subplot

Multiple Plots in a Figure Window

(2,1,1) (2,2,1) (2,2,2)

(2,1,2) (2,2,3) (2,2,4)


Drawing Subplot (Cont.)

Multiple Plots in a Figure Window

(2,2,2)

(2,2,[1 3])

(2,2,4)
Drawing Subplot (Cont.)

Multiple Plots in a Figure Window

>> month=1:10;
>> income = [3.2 4.1 5.0 5.6 6.5 8.1 9 10.5 12 14];
>> outgo = [2.5 4.0 3.35 4.9 5 6.1 4 5.5 7.9 10];
e.g.,
>> subplot(2,1,1)
>> plot(month,income,'- - r s')
>> subplot(2,1,2)
>> plot(month,outgo,'- b o')
Plotting Functions

Function Explanation

line(X,Y) Plot continuous line by using vertices in vector X

line(X,Y,Z) and vector Y.

patch(X,Y,’color’) Plot continuous colored line or color filled polygon

patch(X,Y,[1 0]) by using vertices in vector X and vector Y.

Plot continuous colored line or color filled polygon


fill (X,Y,’color’)
by using vertices in vector X and vector Y.
Plotting Functions (Cont.)

Function Explanation

Plot 3D continuous colored line or color filled


fill3(X,Y,Z,’color’)
polygon by using vertices in vector X and vector Y.

Plot stream particles on 2D or 3D line defined by


streamparticles(C)
vertices assigned in an cell array.

e.g.,
C= { [1,2], [6,-1], [5,7], [10,2]}
streamparticles(C)
Plotting Functions (Cont.)

Function Explanation Example

Plot function given in the


>> ezplot('x^2+y^2-1')
ezplot(‘fucntion’) parenthesis with default axis
>> axis square
limits [-2 2].

>> ezpolar('x^2+1')
Plot polar graph for the given
>> ezpolar('sin')
ezploar(‘function’) function (r=f()) with default
>> ezpolar(@cos)
axis limits [0 2].
>> ezpolar('2*x-1‘)
Plotting Functions (Cont.)

Function Explanation Example

>> ezmesh('x^2+y^2+1')
Plot mesh graph for the
>> ezmesh('x^2+1')
ezmesh('function‘) given with default axis limits
>> ezmesh('2*y+6')
[0 2].
>>ezmesh('x^2-3*y-2')

Plot mesh-contour graph for >> ezmeshc('x^2+y')


ezmeshc('function')
the given with default axis >> ezsmeshc('x^2-y^2')

limits [0 2]. >> ezmesc('x^2+y^2-1‘)


Plotting Functions (Cont.)

Function Explanation Example

Plot surface-contour graph for >> ezsurfc('x^2+y')

ezsurfc('function‘) the given with default axis limits >> ezsurfc('x^2-y^2')


[0 2]. >>ezsurfc('x^2+y^2-1‘)

Plot contour for the given >> ezcontour('x^2+y^2-1')

ezcontour('function‘) function (z=f(x,y)) with default >>ezcontour('x^2-y^2')

axis limits [0 2]. >> ezcontour('x^2-sin(y)‘)


Plotting Functions (Cont.)

Function Explanation Example

>> ezcontour('x^2+y^2-1')
The same as ezcontour but it
ezcontourf('function‘) >>ezcontour('x^2-y^2')
has color filled in the contour.
>> ezcontour('x^2-sin(y)‘)

>>X=[1:0.1:100];
comet(X,Y,) >>Y=sin(X);
To draw animate plot
comet(X,Y,p) >>comet(X,Y)
>>comet(X,Y,0.5)
Plotting Functions (Cont.)

Function Explanation Example

comet3(X,Y,Z)
To draw animate plot >>
comet3(X,Y,Z,p)

To record the image as a frame


getframe >> M(i)=getframe
in series

To make the recorded frame as a


movie >> movie(M)
movie
Curve Fitting Toolbox

Applications

 Reduce noise and smooth data

 Find the mathematical relationship or function among variables

and use that function to perform further data processing.


Curve Fitting Toolbox (Cont.)

>> cftool
Curve Fitting Toolbox (Cont.)

Least Square Method

Set desired y=f(x) For example y=aX+b

Eri= f(xi)-yi

SSE = Sum of Error Square= (f(xi)-yi)2


 f ( x i )  y i 
2
Coefficient of Determination R 
2

 i  y  y 2


Adjusted R  1  
2 1  R 2
 n  1 

 n  k  1 
n= number of data point
k= number of variables excluding constant
Curve Fitting Toolbox (Cont.)

Types of Curve Fitting

Smooth No equation

Y=aX+b Look at only


Linear coefficients
Y=aX2+bX+C

Y=aebX
Non-Linear
Y=aXb
Curve Fitting Toolbox (Cont.)

Types of Curve Fitting

Normal

Linear Least Absolute Residual (LAR)

Robust Bisquare

Normal

Non-Linear Least Absolute Residual (LAR)

Robust Bisquare
Curve Fitting Toolbox (Cont.)

Methods of Curve Fitting

1 n
LES  f ( x i )  y i 2
n i 1

1 n
LAR 
n i 1
w i f(xi )  y i

1 n
Bisquare  i i i
w f ( x )  y 2

n i 1
Curve Fitting Toolbox (Cont.)

LAR and Bisquare

Use LS method to find


new coefficients
Start

Use LS method to
Check Yes
find coefficients
convergence
of coefficients
End
Update wi No
Curve Fitting Toolbox (Cont.)

Commonly Used Methods

 Custom Equation
 Linear
 Polynomial
 Exponential
 Power
 Rational
 Gaussian
Chapter End Exercise

1. Write a function M-file to draw an ellipse with given length of major and

minor axes at given location.

a b

d
>> ezellipse (12,6, x,y)
Chapter End Exercise

2. Write a function M-file to draw an hexagon with a given radius at given

location (x,y).

>> ezhexagon (6, x,y)


Chapter 5

Using Symbolic Toolbox


Chapter Objectives

■ To get familiar with MATLAB symbolic toolbox by answering the


following questions,
What is symbolic toolbox?
Why we need symbolic calculation?

■ To practice on mathematical operation in MATLAB symbolic


toolbox
Symbolic Algebra

syms & sym

>> syms x y z
>> y=x;
>> z=2*x;
>> y+z >> E=sym('2*x+y‘)

ans = E=

3*x 2*x + y
Symbolic Algebra

Numerator & Denominator

>> syms x y
>> y=(2*x+2)/(4*x-5);
>> syms x y;
>> [n,d]=numden(y)
>> A=x/y+y/x;
n=
>> [n,d]=numden(A)
2*x + 2
n=
d=
x^2 + y^2
4*x - 5
d=
x*y
Symbolic Algebra

Expending and Factoring

>> syms x y
>> A=2*(x+y)^2;
>> expand(A)
>> B=x^2+x-2;
ans =
>> factor(B)
2*x^2 + 4*x*y + 2*y^2
ans =
(x + 2)*(x - 1)
Symbolic Algebra

Simplification

>> E=sym('(x+1)*(x-1)‘)
E=
(x - 1)*(x + 1)
>> simplify(E) >> F=sym('x^3-1=(x+3)*(x-3)‘)

ans = F=

x^2 - 1 x^3 - 1 == (x - 3)*(x + 3)


>> simplify(F)
ans =
x^3 + 8 == x^2
Symbolic Algebra

Collecting Like Terms

>> syms x y
>> Z=x^2+y+x*y-2*x^2-5+2*x*y+4
Z=
- x^2 + 3*y*x + y - 1
>> collect(Z)
>> w = sym('x^3-1 = (x-3)*(x+3)');
ans =
>> collect(w)
- x^2 + 3*y*x + y - 1
ans =
x^3 - 1 == x^2 - 9
Symbolic Algebra

Solve Function

>> solve('a*x^2+b*x+c')
ans =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
>> solve('x^2-1==0‘)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
ans =
1
>> solve('x^2-1==3‘)
-1
ans =
2
-2
Symbolic Algebra

Solve Function

>> syms x y a b
>> solve(x^2+a*x+b,’a’)
ans = >> Eq=sym('P = P0*exp(r*t)')
-(x^2 + b)/x Eq =
P == P0*exp(r*t)
>> solve(Eq,'t')
ans =
log(P/P0)/r
Symbolic Algebra

Solving System of Linear Equations

>> Eq1=sym('3*x + 2*y -z = 10'); >> answer.x


>> Eq2= sym('-x + 3*y + 2*z = 5'); ans =
>> Eq3=sym('x - y - z = -1'); -2
>> answer=solve(Eq1,Eq2,Eq3) >> answer.y
answer = ans =
x: [1x1 sym] 5
y: [1x1 sym] >> answer.z
z: [1x1 sym] ans =
-6
Symbolic Algebra

Solving System of Linear Equations

>> Eq1=sym('3*x + 2*y -z = 10');

>> Eq2= sym('-x + 3*y + 2*z = 5');

>> Eq3=sym('x - y - z = -1');

>> [x,y,z]=solve(Eq1,Eq2,Eq3)
Symbolic Algebra

Substitution

>> Eq=sym('2*x=1')

Eq =
>> subs(Eq,3)
2*x == 1
ans =
>> subs(Eq,'y‘) 6 == 1

ans =

2*y == 1
Symbolic Algebra

Substitution

>> syms a b c d e

>> Eq=a+ b+ c+ d;

>> subs(Eq,{a, b, c, d},{1, 2, 3, 4})

ans =

10
Symbolic Algebra

Symbolic Plot

ezplot(‘fucntion’) >> y=sym('x^2+1');


ezplot(‘fucntion’, [xmin xmax]) >> ezplot(y)

>> ezplot('x^2-1') >>ezplot('x^2+y^2=1',[-1.5 1.5])


>> ezplot('x^2-1',[-10 10])

>> y=@(x) x.^2-1;


>>ezplot(y)
Numerical Integration

Integrating

>> syms x y >> syms x y

>> int(x^2+1) >> int(x^2+1,2,3)

>>int(x^2+1,x) >>int(int(x^2+1,2,3),y,4,5)

>>int(x^2+1,y)

>>int(int(x^2+1,x),y)
Numerical Integration

Differentiation

>> syms x y >> diff(x^2+1,x,2)


>> diff(x^2+1) ans =
ans = 2
2*x
>> diff(x^2+1,y)
ans =
0
Numerical Integration

Integrating of Differential Equation

>>dsolve('Dy=2*x+1') >> dsolve('Dy=2*t+1','y(0)=0')


ans = ans =
C13 + t*(2*x + 1) t*(t + 1)

>> dsolve('Dy=2*x+1','x')
ans =
C15 + x*(x + 1)
Chapter 6

Numerical Analysis with MATLAB


Chapter Objectives

■ To get familiar with numerical analysis by answering the following


questions,
What is numerical analysis?
What is numerical method?
Why we need numerical analysis?

■ To practice on different numerical calculation functions available in


MATLAB which are commonly used in engineering applications.

■ To practice on MATLAB programming based on numerical


methods.
What is Numerical Analysis?

Numerical Analytic

Experiment
What is Numerical Analysis?

A Special Example

Time Velocity
(s) (m/s)
dv C
 g  d v2 0 0.0000
dt m
2 18.7292
4 33.1118
By integral 6 42.0762
8 46.9575
gm  gC d  10 49.4214
v( t )  tanh  t 
Cd  m  12 50.6175
 51.6938
What is Numerical Analysis?

A Special Example
Time Velocity
(s) (m/s)
dv v v( t i 1 )  v( t i )
  0 0.0000
dt t t i 1  t i
2 19.6200

v ( t i 1 )  v ( t i ) C 4 36.6417
 g  d v( t i ) 2
t i 1  t i m 6 46.2983

8 50.1802
 Cd 
v ( t i 1 )  v ( t i )   g  v( t i )2 ( t i 1  t i ) 10 51.3123
 m 
12 51.6008
At t=0, v=0
 51.6938
What is Numerical Analysis?

A Special Example

Velocity Velocity
Time
(m/s) (m/s) Error
(s)
(Exact) (Approximate)
0 0.0000 0.0000 0
2 19.6200 18.7292 0.8908
4 36.6417 33.1118 3.5299
6 46.2983 42.0762 4.2221
8 50.1802 46.9575 3.2227
10 51.3123 49.4214 49.4214
12 51.6008 50.6175 50.6175
 51.6938 51.6938 0
What is Numerical Analysis?

A Special Example

60
Approxmiate
50
Exact solution
40
Velocity (m/s)

30

20

10

0
0 2 4 6 8 10 12
Time (s)
Selected Topics

Interpolation

Finding Roots

Solutions for Systems of Linear Equations

Numerical Integration

Numerical Differentiation

Numerical Integration of Differential Equation


Interpolation

What is Interpolation?

x y = f(x)

3 7

5 8.1

6.5 9

x=4.2 y=?
Interpolation (Cont.)

Methods

■ Newton Interpolating Polynomial

(1) Linear Interpolation

(2) Quadratic Interpolation

■ Lagrange Interpolating Polynomial


Interpolation (Cont.)

Newton Interpolating Polynomial

(1) Linear Interpolation

f ( x 2 )  f ( x1 )
f ( x )  f ( x1 )  ( x  x1 )
x 2  x1

(2) Quadratic Interpolation

f ( x )  b1  b2 ( x  x1 )  b3 ( x  x1 )( x  x 2 )

b1  f ( x1 ) f ( x 3 )  f ( x 2 ) f ( x 2 )  f ( x1 )

f ( x 2 )  f ( x1 ) x3  x2 x 2  x1
b2  b3 
x 2  x1 x 3  x1
Interpolation (Cont.)

Lagrange Interpolation

y  L 1y 1  L 2 y 2
x y = f(x)
x  x2
L1 
x1  x 2 3 7

x  x1 5 8.1
L2 
x1  x 2
6.5 9
x  x2 x  x1
f(x)  y1  y2
x1  x 2 x 2  x1
Interpolation (Cont.)

MATLAB functions

Yq = interp1(X,Y,Xq) Vq = interp2(X,Y,V,Xq,Yq)

Yq = interp1(X,Y,Xq,’method’) Vq = interp3(X,Y,Z,V,Xq,Yq,Zq)

'nearest' - nearest neighbor interpolation


'linear' - linear interpolation
'spline' - piecewise cubic spline interpolation (SPLINE)
'pchip' - shape-preserving piecewise cubic interpolation
'cubic' - same as 'pchip‘
'v5cubic' - the cubic interpolation from MATLAB 5, which does
not extrapolate and uses 'spline' if X is not equally
spaced.
Interpolation (Cont.)

Nearest Interpolation

x y = f(x)
9 
 3 7
8
7 
5 8.1

6.5 9

3 5 6.5
Interpolation (Cont.)

Newton Interpolating Polynomial (Example)

ln(1)=0;

ln(6)=1.791759

ln(4)=?

ln(1)=0;

ln(4)=1.386294

ln(6)=1.791759

ln(2)=?
Root Finding

Roots

f(x)=0

f1(x) f2(x) f3(x)=0

 b  b 2  4 ac
x1 , x 2 
2a

ax2+bx+c=0

C1x4+C2x3+C3x2+C4x+C5=0
Root Finding (Cont.)

MATLAB functions

>> roots (C)

>>fzero(funciton, x0)

>>fzero(funciton, [x0 x1] )

>> solve(‘f(x)==0’)
Root Finding (Cont.)

Methods

Graphical Method

Bracketing Method

Bisection Method

False Position Method

Simple Fixed Point Iteration

Newton-Raphson Iteration

Secant Method
Root Finding (Cont.)

Graphical Method

x=[………………]

f(x)= […………….]

plot (x, f(x))


Root Finding (Cont.)

Bracketing Method (Incremental Search)

x=[x1, x2,x3,x4…….xmax]
F(x1)=?
F(x2)=?
If f(x1)*f(x2)<0;
[x1 x2]
end
Root Finding (Cont.)

Bisection Method


Start with xmin xmax xmax
xmin
Bisect the interval xmid=(xmin+xmax)/2
Find f(xmin), f(xmax), f(xmid)

If f(xmin)*f(xmid)<0
xmin xmax
xmax=xmid
bisect

elseif f(xmid)*f(xmax)<0
xmin xmax
xmin=xmid
bisect
else
end
Go until (xmax-xmid)< tolerance
or (xmid-xmin)<tolerance
Root Finding (Cont.)

False Position Method

f ( x u )( x l  x u )
xr  xu 
f ( xl )  f ( xu )

If f(xr)*f(xu)<0
xl=xr
Find xr again
elseif f(xr)*f(xl)<0
xu=xr
Find xr again
end
Go until (xu-xl)< tolerance
Root Finding (Cont.)

Simple Fixed Point Iteration

Guess initial xn
f( x)  0
f ( x)  x  x Then find xn+1

g( x )  x Reset xn=xn+1

g( x n )  x n 1 Go until (xn- xn+1)

x n 1  g( x n )
Root Finding (Cont.)

Newton-Raphson Iteration Method

f ( x0 )
ax 2  bx  c  0 x1  x 0 
f ' ( x0 )
f ( xn ) f ( x1 )
x n 1  x n  x 2  x1 
f ' ( xn ) f ' ( x1 )

Initiate or Guess=x0 Convergence tolerance=x2-x1<0.001


Root Finding (Cont.)

Secant Method

 xn f ( xn )
x n 1  x n 
f ( x n  x n )  f ( x n )

Initiate or Guess=x0 Convergence tolerance=x2-x1<0.001

 Perturbation fraction,  =110-6


Solutions of Linear Equations

System of Linear Equations

f(x1,x2,x3,….xn)=0 (1)

f(x1,x2,x3,….xn)=0 (2)

f(x1,x2,x3,….xn)=0 (3)

a11x1+ a11x2 + a11x3 + ….. + a1nxn =0 (1)

a21x1+ a22x2 + a23x3 + ….. + a2nxn =0 (2)

a31x1+ a32x2 + a33x3 + ….. + a3nxn =0 (3)


Solutions of Linear Equations

System of Linear Equations

10 I1 - 9 I2=100 (1)
System of linear
-9 I1 + 20 I2 - 9 I3=0 (2)
equation
-9 I2 + 15 I3=0 (3)
Solutions of Linear Equations (Cont.)

Solving Methods

Graphical Method

Matrix Inverse Method

Cramer’s Rule

Gauss Elimination Method

LU Factorization

Cholesky Factorization

Gauss-Shidel Iteration Method


Solutions of Linear Equations (Cont.)

Graphical Method

x2
3x1+2x2=18 (1)

-x1+x2=2 (2)
(x2,x1)
x2=f1(x1)


x2=f2(x1)

plot(x2,x1)
x1
Solutions of Linear Equations (Cont.)

Matrix Inverse Method

A * X =C
3x1+2x2=18
A *A-1 X = A-1 * C

I* X = A-1 * C -x1+x2=2

X = A-1 * C

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

>> C=[18; 2];

>> X=inv(A)*C
Solutions of Linear Equations (Cont.)

Cramer’s Rule

a 11 a 12 a 13   x1   c1 
a a 22 a 23  x 2   c 2 
 21
a 31 a 32 a 33   x 3  c 3 

det( A )  ?

 c1 a 12 a 13  a 11 c1 a 13  a 11 a 21 c1 
c a 22 a 23  a c2 a 23  a a 22 c 2 
 2  21  21
c 3 a 32 a 33  a 31 c3 a 33  a 31 a 32 c 3 
x1  x2  x3 
det( A ) det( A ) det( A )
Solutions of Linear Equations (Cont.)

Cramer’s Rule (Exercise)

0.3 0.52 1   x1    0.01


0.5 1 1.9  x    0.67 
   2  
 0.1 0.3 0.5  x 3   0.44

det( A )  ?

 c1 a 12 a 13  a 11 c1 a 13  a 11 a 21 c1 
c a 22 a 23  a c2 a 23  a a 22 c 2 
 2  21  21
c 3 a 32 a 33  a 31 c3 a 33  a 31 a 32 c 3 
x1  x2  x3 
det( A ) det( A ) det( A )
Solutions of Linear Equations (Cont.)

Gaussian Elimination Method

a 11 a 12 a 13   x1   c1 
a a 22 a 23  x 2   c 2 
 21
a 31 a 32 a 33   x 3  c 3 

a a 32
st
1 Round R 2  21 R 1 nd
2 Round R3  R2
a 11 a 22
a 31
R3  R1 [Forward elimination]
a 11
Solutions of Linear Equations (Cont.)

Gaussian Elimination Method

a 11 a 12 a 13   x1   c1 
0 a 22 a 23  x 2   c 2 

 0 0 a 33   x 3  c 3 

c c 2  a 23 x 3
1 Round x 3  3
st 2 nd Round x 2 
a 33 a 22

c1  a 13 x 3  a 12 x 2 [Backward substitution]
3rd Round x1 
a 11
Solutions of Linear Equations (Cont.)

LU Factorization

AX  C a 11 a 12 a 13 
U   0 a '22 a '23 
 0 0 a "33 
U L 
1 0 0
LD  C L  f 21 1 0
f 31 f 32 1

UX  D a
f 21  21
a
f 31  31
a '32
f 32  '
a 11 a 11 a 22
Solutions of Linear Equations (Cont.)

LU Factorization

a 11 a 12 a 13 
A  a 21 a 22 a 23 
a 31 a 32 a 33 

1 0 0 a 11 a 12 a 13 
L  f 21 1 0 U   0 a '22 a '23 
f 31 f 32 1  0 0 a "33 

>>[L,U]=lu(A)
Solutions of Linear Equations (Cont.)

LU Factorization (Example)

 3  0.1  0.2  7.85 


A  0.1 7  0.3 C   19.3
0.3  0.2 10   71.4 

>> A=

>> [L, U]=lu(A)  3 


X   2.5
>> D=inv(L)*C  7 

>>X=inv(U)*D
Solutions of Linear Equations (Cont.)

Cholesky Factorization

a 11 a 12 a 13  UT [ D]  [ C]
A  a 21 a 22 a 23 
a 31 a 32 a 33  U[ X ]  [ D]
i 1
u 11 u 12 u 13  u ii  a ii   u ki
U   0 u 23 
k 1
u 22
i 1
 0 0 u 33  a ij   u ki  u kj
u ij  k 1
u ii
Solutions of Linear Equations (Cont.)

Cholesky Factorization (Example)

 3  0.1  0.2  7.85 


A  0.1 7  0.3 C   19.3
0.3  0.2 10   71.4 

>> A=
>> C=
 3 
>> [U]=chol(A) X   2.5
>> D=inv(U’)*C  7 

>>X=inv(U)*D
Solutions of Linear Equations (Cont.)

Gauss-Shidel Method

c1  [ a 12 x 2  a 13 x 3  ...  a 1n x n ]
x1 
a 11
Assume c 2  [ a 21x1  a 23 x 3  ...  a 2 n x n ]
x2 
x1,x2,x3,…, xn a 22
n 1
c n   a nk x k
xn  k 1 (nk)
a nn
Solutions of Linear Equations (Cont.)

Gauss-Shidel Method with Relaxation

x i  x i  (1   )x i 1

= 1 ~ 2
Solutions of Linear Equations (Cont.)

Matrix Left Division

A * X =C

X = A\C

3x1+2x2=18
>> A=
-x1+x2=2
>> C=

>> X=A\C

>> X=mldivide(A,C)
Solutions of Linear Equations (Cont.)

Direct Methods (Matrix Left Division)


Numerical Integration

Integration

I   f ( x ) dx I   f ( x, y ) dx dy

I   f ( x, y , z ) dx dy dz

b
I   f ( x ) dx I   f ( x ) dx I   f ( x, y )
a
Numerical Integration

Integrating in MATLAB

>> syms x y >> syms x y

>> int(x^2+1) >> int(x^2+1,2,3)

>>int(x^2+1,x) >>int(int(x^2+1,2,3),y,4,5)

>>int(x^2+1,y)

>>int(int(x^2+1,x),y)
Numerical Integration (Cont.)

Integrating in MATLAB

>> integral(F, L,U)

>>integral2(F,Lx,Ux,Ly,Uy)

>>integral3(F,Lx,Ux,Ly,Uy, Lz,Uz)

>> F=@(x) x.^2+1


Numerical Integration (Cont.)

Methods

Trapezoidal Rule

Recursive Trapezoidal Rule ***

Simpson’s Rule (1/3 rule)

Simpson’s Rule (3/8 rule)

Adaptive Simpson’s Rule ***


Numerical Integration (Cont.)

Trapezoidal Rule

Y=f(x)
b
I   f(xi )
a f(x)
n 1 f(a)
f ( x 0 )  2 f ( x i )  f ( x n ) f(b)

I  b  a  i 1
2n
h

(b  a) x i 1  x i  h
h
n a b x
Numerical Integration (Cont.)

Trapezoidal Rule

>> trapz(Y)

>> trapz(X,Y)
>> X=[0:0.2:1];

>> Y=X.^2+1;

>>trapz(X,Y)

>>cumtrapz(X,Y)
Numerical Integration (Cont.)

Simpson’s Rule (1/3) Y=f(x)

f(x)
b f(a)
I   f(xi ) f(b)
a

h
(b  a) x i 1  x i  h
h
n
a b x
n 1 n 2
f ( x0 )  4  f ( x i ) 2  f ( x j )  f ( xn )
I  b  a  i 1, 3 , 5 i 2, 4 ,6

3n
Numerical Integration (Cont.)

Simpson’s Rule (3/8) Y=f(x)

f(x)
b f(a)
I   f(xi ) f(b)
a

h
(b  a) x i 1  x i  h
h
n
a b x

3h  n 1 n 2

I 
8 
f ( x 0 )  3  f ( x i )  2  f ( x j )  f ( x )
n 
i 1, 3, 5 i 2 , 4 ,6 
Numerical Integration (Cont.)

Adaptive Simpson’s Rule

I1 
a c b

I2   
a b
c

1
( I 2  I1 )  
15

     
a c
c b

1 1
( I 2  I1 )   / 2 ( I 2  I1 )   / 2
15 15
Numerical Integration (Cont.)

Simpson’s Rule (3/8)

>> quad(F, L,U)

>>quad2d(F,Lx,Ux,Ly,Uy)

>>quadgk(F,L,U)

>> F=@(x) x.^2+1


Numerical Differentiation (Cont.)

Differentiation in Engineering and Science

y  f(x)

dy df ( x )

dx dx
v  f(t )

v=Velocity dv df ( t )
a( t )  
a=Acceleration dt dt
Numerical Differentiation (Cont.)

Differentiation in Engineering and Science

dy df ( x )
  2x
dx dx

y  f ( x)  x2  1

dy df ( x ) f ( x i  x )  f ( x i )
 
dx dx x
Numerical Differentiation (Cont.)

Differentiation in Engineering and Science

f  2f x 2  nf x n
f ( x  x )  f ( x )  x  2  ..... n
x x 2! x n!

f df f ( x  x )  f ( x )
 
x dx x

Forward Difference
Numerical Differentiation (Cont.)

Taylor Series

At x=a;

f ( a )  2f ( a ) ( x  a )2
f(x)  f(a )  (x  a)   ....
x x 2
2!
 nf ( a ) ( x  a )n
At x=xi+x; 
x n n!

?
Numerical Differentiation (Cont.)

Taylor Series

>>taylor(f)

>>taylor(f,x)

>>taylor(f,x,a)

Fifth order Taylor polynomial approximation of

a function, f(x), about the point x=0.


Numerical Differentiation (Cont.)

Finite Difference Approximation by Taylor’s Series

f f ( x i 1 )  f ( x i )
 First order, Forward
x x difference

f f ( x i )  f ( x i 1 )
 First order, Backward
x x difference

f f ( x i 1 )  f ( x i 1 )
 Second order, Central
x 2x difference
Numerical Differentiation (Cont.)

Finite Difference Approximation by Taylor’s Series

f f
? ?
x y
 2f  2f
? ?
x 2
y 2

 2f
?
xy
Numerical Differentiation (Cont.)

Finite Difference Approximation by Taylor’s Series

>> sin(2*pi*0.2) 0.9511


>> diff(X)
>> sin(2*pi*0.22) 0.9823
>> diff(X,N) >> y=[0.9511 0.9823];
>> x=[0.2 0.22]
e.g., >> df=diff(y)/diff(x) 1.5600

f ( x )  sin( 2x )
f ( x )
 2 cos( 2x ) 1.1774
x
Numerical Differentiation (Cont.)

Finite Difference Approximation by Taylor’s Series

>> gradient (A)

>>gradient(A,x)

>> [Fx,Fy]=gradient (A)

>> f f ( x i 1 )  f ( x i 1 )

x 2x
Numerical Integration of ODE

ODE (Ordinary Differential Equation)

dy
 y'  f ( y , t ) Initial Value Problem
dt

y   y'  ? y'  f ( y , t )

y( 0 )  C
Numerical Integration of ODE (Cont.)

ODE (Ordinary Differential Equation)

>>dsolve('Dy=2*x+1') >> dsolve('Dy=2*t+1','y(0)=0')


ans = ans =
C13 + t*(2*x + 1) t*(t + 1)

>> dsolve('Dy=2*x+1','x')
ans =
C15 + x*(x + 1)
Numerical Integration of ODE (Cont.)

ODE (Ordinary Differential Equation)

>> dsolve('D2y=2*t‘)
ans =
t^3/3 + C2*t + C3

>> dsolve('D2y=2*t','Dy(0)=0','y(0)=0')
ans =
t^3/3
Numerical Integration of ODE (Cont.)

Methods

Euler’s Method

Heun’s Method

The Midpoint Method

Runge-Kutta Method
Numerical Integration of ODE (Cont.)

Euler’s Methods

dy
y'   f (t, y ) ( Given )
dt
y 0  y( 0 )  C ( Given )
t  t0 ~ tf

y i 1  y i  y 'i h
h  t i 1  t i
y i 1  y i  f ( t i , y i )h
Numerical Integration of ODE (Cont.)

Euler’s Methods (Example)

y '  4e 0.8 t  0.5y

t  0~4 s Exact Solution


At t 0  y( 0 )  2 4 0.8 t 0.5t
y ( e  e )  2e 0.5t
1.3
y( 0 )  2 y  6.1946

y ' ( 0 )  f ( 0,2 )  3
y(1)  2  f ( 0,2 )(1)  5
Numerical Integration of ODE (Cont.)

Heun’s Method

dy
y'   f ( t , y ) ( Given )
dt
y i 1  y i  y 'i ,avg h
y 0  y( 0 )  C ( Given )
t  t 0 ~ tf y0  C
y '0  f ( t 0 , y 0 )
y 1  y 0  y '0 h
h  t i 1  t i
y 1'  f ( t 1 , y 1 )
y '0 ,avg  ( y '0  y 1' ) / 2
Numerical Integration of ODE (Cont.)

Heun’s Method (Example)

Exact Solution
y  4e
' 0.8 t
 0.5y
4 0.8 t 0.5t
t  0~4 s y ( e  e )  2e 0.5t
1.3
At t  0  y( 0 )  2 y  6.1946

y( 0 )  2 y '0  y 1' 3  6.4022


y '0 ,avg  
y ' ( 0 )  y '0  f ( 0,2 )  3 2 2
y(1)  y 1  y 0  y '0 h  5 y(1)  y 1  y 0  y '0,avg h  6.7011
y ' (1)  y 1'  f (1,5)  6.4022
Numerical Integration of ODE (Cont.)

The Midpoint Method

dy
y'   f ( t , y ) ( Given )
dt
y 0  y( 0 )  C ( Given ) h
y i 1/ 2  y i  f(t i , y i )
t  t 0 ~ tf 2
y 'i1/ 2  f ( t i 1/ 2 , y i 1/ 2 )
y i 1  y i  f ( t i 1/ 2 , y i 1/ 2 )h
h  t i 1  t i
Numerical Integration of ODE (Cont.)

The Midpoint Method (Example)

y '  4e 0.8 t  0.5y


Exact Solution
t  0~4 s
At t  0  y( 0 )  2 4 0.8 t 0.5t
y ( e  e )  2e 0.5t
1.3
1 y  6.1946
y i 1/ 2  2  f ( t i , y i )   3.5
2
y 'i1/ 2  f ( 0.5,3.5 )  4.2173
y i 1  2  4.2173 1  6.2173
Numerical Integration of ODE (Cont.)

Runge-Kutta Method (Second Order Method)

h  t i 1  t i
y i 1  y i  ( a 1k 1  a 2 k 2 )h
k1  f(t i , y i )
a2=1/2
k 2  f ( t i  p1h , y i  q 11k 1h )
a2=1
a1  a 2  1
a 2 p1  1 / 2 a2=2/3

a 2 q 11  1/ 2

Midpoint method
Numerical Integration of ODE (Cont.)

Runge-Kutta Method (Third Order Method)

1
y i 1  y i  ( 2k 1  3k 2  4 k 3 )h
9
k1  f(t i , y i )
1 1 h  t i 1  t i
k 2  f ( t i  h , y i  k 1h )
2 2
3 3
k 3  f ( t i  h, y i  k 2h )
4 4
Numerical Integration of ODE (Cont.)

Runge-Kutta Method (Forth Order Method)

1
y i 1  y i  ( k 1  2k 2  2k 3  k 4 )h
6
k1  f (t i , y i )
1 1
k 2  f ( t i  h , y i  k 1h ) h  t i 1  t i
2 2
1 1
k 3  f ( t i  h, y i  k 2h )
2 2
k 4  f ( t i  h , y i  k 3h )
Numerical Integration of ODE (Cont.)

Runge-Kutta Method (Forth Order Method) (Example)

Exact Solution
y  4e
' 0.8 t
 0.5y
4 0.8 t 0.5t
t  0~4 s y ( e  e )  2e 0.5t
1.3
At t  0  y( 0 )  2 y  6.1946

k 1  f ( 0, 2 )  3 1
y 1  2  ( 3  2  4.2173
k 2  f ( 0.5,3.5 )  4.2173 6
k 3  f ( 0.5, 4.1086) 3.9130 2  3.9130  5.9457)

k 4  f (1, 3.9565) 5.9457 y 1  6.2010


Numerical Integration of ODE (Cont.)

Runge-Kutta Method (Fifth Order Method)

1
y i 1  y i  ( 7k 1  32k 3  12k 4  32k 5  7k 6 )h
90
k1  f(t i , y i )
1 1
k 2  f ( t i  h , y i  k 1h )
4 4
1 1 1
k 3  f ( t i  h , y i  k 1h  k 2 h )
4 8 8
1 1 h  t i 1  t i
k 4  f ( t i  h , y i  k 2 h  k 3h )
2 2
3 3 9
k 5  f ( t i  h , y i  k 1h  k 4 h )
4 16 16
3 2 12 12 8
k 6  f ( t i  h , y i  k 1h  k 2 h  k 3h  k 4 h  k 5 h )
7 7 7 7 7
Numerical Integration of ODE (Cont.)

MATLAB functions for solving ODE

[t, y]=ode23(F, tspan, y0)

>> dydt=@(t,y) 4*exp(0.8*t)-0.5*y;


>> [t,y]=ode23(dydt,[0:4],2)
Numerical Integration of ODE (Cont.)

MATLAB functions for solving ODE

[t, y]=ode45(F, tspan, y0)

>> dydt=@(t,y) 4*exp(0.8*t)-0.5*y;


>> [t,y]=ode45(dydt,[0, 3, 6, 7, 10, 16],2)
Numerical Integration of ODE (Cont.)

MATLAB functions for solving ODE


Numerical Integration of ODE (Cont.)

MATLAB functions for solving ODE

[t, y]=ode23(F, [t1 t2 t3 t4 t5], y0)

>> dydt=@(t,y) 4*exp(0.8*t)-0.5*y;


>> [t,y]=ode23(dydt,[0 1 3 4 6 10],2)
Numerical Integration of ODE (Cont.)

System of ODE

dy 1
 f1( t , y 1 , y 2 ,...,y n )
dt
dy 2
 f1( t , y 1 , y 2 ,...,y n )
dt
dy 3
 f1( t , y 1 , y 2 ,...,y n )
dt
.
.
.
dy n
 f1( t , y 1 , y 2 ,...,y n )
dt
Numerical Integration of ODE (Cont.)

System of ODE (Example)

dx 2 Initial condition
 t  2t
dt
x=0 at t=0
dv
 2t  2 v=0 at t=0
dt
Numerical Integration of ODE (Cont.)

System of ODE (Example)

>> dxdt=@(t,x) t^2+2*t;

>> dvdt=@(t,x) 2*t+2;

>> [t,x]=ode45(dxdt,[0:4],0)

>> [t,v]=ode45(dvdt,[0:4],0)
Numerical Integration of ODE (Cont.)

System of ODE (Example)

function [y] =test(F,a,b);

y=F(a)+F(b);

end

>>test(@sin,2,3)
Numerical Integration of ODE (Cont.)

System of ODE (Example)

dy 1
 1.2 y 1  0.6y 1y 2
dt
dy 2
 0.8 y 2  0.3y 1y 2
dt

y1= 2 at t=0

y2=1 at t=0
Numerical Integration of ODE (Cont.)

System of ODE (Example)

function [dydt] =F(t,y)

dydt=[1.2*y(1)-0.6*y(1)*y(2);-0.8*y(2)+0.3*y(1)*y(2)];

end

[t,y]=ode45(@F,[0:4],[2 1])
Numerical Integration of ODE (Cont.)

System of ODE (Example)

d 2 y1 2 dy 1
2
 ( 1  y 1)  y1  0
dt dt y1  1 at t=0
dy 1
dy 1 y2   1 at t=0
 y2 dt
dt

dy 2
 (1  y 12 )y 2  y 1  0
dt
Numerical Integration of ODE (Cont.)

System of ODE (Example)

function [dydt] =F(t,y)

dydt=[y(2);1*(1-y(1)^2)*y(2)-y(1)];

end

[t,y]=ode45(@F,[0:20],[1 1])
Numerical Integration of ODE (Cont.)

Boundary Value Problem

d2 y1  BC 1
2
 f ( t , y 1, .....)
dt  BC 2
t1 t

d2 y1
2
 f ( t , y 1, .....)  BC2
dt
 BC1
t1 t
Numerical Integration of ODE (Cont.)

Boundary Value Problem


T=200 h=0.05

d2T
2
 h ( T  T )  0
dx

dT
z x=0 x=L
dx
dz T(0)=300 T(L)=400
 h( T  T )
dx
dz
 0.05( 200  T )
dx
Numerical Integration of ODE (Cont.)

Boundary Value Problem


T=200 h=0.05

dT
z
dx

dz
 0.05( 200  T ) x=0 x=L
dx
T(0)=300 T(L)=400

T=300 at x=0

Z=-5 at x=0
Numerical Integration of ODE (Cont.)

Boundary Value Problem

z (0)= ?

z=-5 T(L)= 569

z=-20 T(L)= 259.51

z=? T(L) = 400

Use slope equation since it is linear equation.


Numerical Integration of ODE (Cont.)

Boundary Value Problem


T=200 h=0.05

T=200
d2T
2
 h ( T  T )  0
dx

dT
z
dx x=0 x=L

dz dT/dx= (T(0)-T) T(L)=400


 h( T  T )
dx
Chapter 6

Creating Graphical User Interface


Chapter Objectives

■ To get familiar with graphical user interface by answering the


following questions,
What is the purpose of GUI?
Where can we use it?
What are the steps to create GUI in MATLAB?
What are GUI components available in MATLAB?

■ To practice on creating GUI in MATLAB for some engineering


applications
GUIs in MATLAB

Purposes of GUIs

The purposes are to

■ allow the user to interact with your program


■ to complete a task in a convenient and faster way

■ to assembly and to see essential input/output data on the

same panel
GUIs in MATLAB (Cont.)

Application of GUIs

It is applicable as a supporting tool for computation and

simulation in

(1) Thesis and Dissertation

(2) Project Reports


GUIs in MATLAB (Cont.)

Steps in Creating GUIs in MATLAB

The three-step approach is as follows.

(1) Designing the layout

(2) Setting properties of GUI components

(3) Programming the GUIs


GUIs in MATLAB (Cont.)

GUI files

GUI

Step 1
Step 3
Step 2

Figure M-file Code M-file


GUIs in MATLAB (Cont.)

Call GUIDE Menu bar Tool bar

>>guide

GUI component
panel

GUI Layout area


GUIs in MATLAB (Cont.)

Adjusting GUI Layout Area

Drag here

Property inspector
GUIs in MATLAB (Cont.)

GUI Components

Pop-up List Box


Menu

Push Slide
Toggle Table
Button
Radio
Check Figure
Button Panel

Editable Static Button Active


Text Text Group X
Control
GUIs in MATLAB (Cont.)

Designing GUI Layout

Drag & Drop


GUIs in MATLAB (Cont.)

Designing GUI Layout (Example)

Daily Traffic Arrival Pattern

Peak Time

Plot
GUI Components

Push Button


Push Button


GUI Components (Cont.)

Push Button

Push button

% --- Executes on button press in pushbutton1.


function pushbutton1_Callback(hObject, eventdata, handles)
Statement 1
Statement 2
Statement a Statements to be done soon after
…xxxxxxxx pressing push button.
…xxxxxxxxxxxx
…xxx
GUI Components (Cont.)

Slider





Slider
GUI Components (Cont.)

Slider

Slider

% --- Executes on slider movement.

function slider1_Callback(hObject, eventdata, handles)

handles.step=get(hObject,'Value')

guidata(hObject, handles);
GUI Components (Cont.)

Radio Button




Radio button


GUI Components (Cont.)

Radio Button

Radio button

% --- Executes on button press in radiobutton1.


function radiobutton1_Callback(hObject, eventdata, handles)
handles.H=get(hObject,'String');
guidata(hObject,handles)

handles.H=get(hObject,‘Value');
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components



Panel


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Panel

% --- Executes when selected object is changed in uipanel1.


function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
handles.H=get(hObject,’String')
guidata(hObject,handles)

handles.H=get(hObject,‘Value');
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components


Check Box


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Check Box

% --- Executes on button press in checkbox1.


function checkbox1_Callback(hObject, eventdata, handles)
handles.H=get(hObject,'Value')
guidata(hObject,handles)

handles.H=get(hObject,‘String')
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components


Editable text


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Editable text

function edit1_Callback(hObject, eventdata, handles)


handles.H=str2double(get(hObject,'String'))
guidata(hObject,handles)

handles.H=get(hObject,'String‘)
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Editable text

handles.H=eval(get(hObject,'string'))
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components



Static text


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components




Pop-up Menu

 


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Pup-up Menu

% --- Executes on selection change in popupmenu1.

handles,H= get(hObject,'Value')

guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components




List box

 


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

List box

% --- Executes on selection change in listbox1.

handles,H= get(hObject,'Value')

guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components




Toggle button


GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Toggle button

% --- Executes on button press in togglebutton1.


function togglebutton1_Callback(hObject, eventdata, handles)
handles.H=get(hObject,'value')
guidata(hObject,handles)
GUIs in MATLAB (Cont.)

Setting the Properties of GUI components

Axes 
Chapter 7

Ccoder and Audio Processing


Chapter Objectives

■ To learn how to convert from MATLAB code to other language


code

■ To learn how to use C-coder to convert MATLAB code to C-


code available in MATLAB
Ccoder

From Apps (Toolbox Menu)


Ccoder (Cont.)

From Command Line Interface

>> Ccoder

Project name

Where you want to save


Ccoder (Cont.)

Configuration of Ccoder
Ccoder (Cont.)

Defining Global Variables


Ccoder (Cont.)

Function M-file vs. Script M-file


Ccoder (Cont.)

Choose Output Type


Ccoder (Cont.)

Building C Code
Ccoder (Cont.)

More Detailed Setting


Ccoder (Cont.)

More Detailed Setting


Ccoder (Cont.)

More Detailed Setting

Location of project folder and build folder


Ccoder (Cont.)

More Detailed Setting

Only for inter operation, floating point operation will not appear

Check, if the algorithm supports for NaN and Inf


Otherwise, uncheck
Ccoder (Cont.)

More Detailed Setting

Set as default setting


Ccoder (Cont.)

More Detailed Setting

To generate code in a single file

Comment style

If else statement to switch statement


Ccoder (Cont.)

More Detailed Setting

To show status of code generation

To create code report

To automatically launch report or not


Ccoder (Cont.)

More Detailed Setting

Product from which company


Product type
Ccoder (Cont.)

More Detailed Setting

Overall
setting
Sound Recording

% Record your voice for 5 seconds.


recObj = audiorecorder;
disp('Start speaking.')
recordblocking(recObj, 5);
disp('End of Recording.');
% Play back the recording.
play(recObj);
% Store data in double-precision array.
myRecording = getaudiodata(recObj);
% Plot the waveform.
plot(myRecording);
Sound Recording (Cont.)

y = getaudiodata(recorder, dataType)

Int8 -128 to 127


uint8 0 to 255
int16 -32768 to 32767
single -1 to 1
double -1 to 1
Think Smarter,
Work Harder !

Thank You

19/6/2015

You might also like