Professional Documents
Culture Documents
(Ccoder)
References
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
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
programming language.
matrix.
Why is MATLAB based on Matrix?
Date= [1 2 3 4 5 …31]
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
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
Tension [Fx1 Fy1 ] F x2 Fy 2 F
x3 Fy3 ...
F
Distance = [2 4 6 8]
Shear force = [Fs1 Fs2 Fs3 Fs4]
[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
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?
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.
1
Without Cell Zooming
CCZ = Continuous Cell
Zooming CCZ with CPU
CCZ with TAPU
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
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 8.5
2016
How to Install MATLAB on PC
2
The MATLAB Desktop (Window)
>> edit
_____.m Extension
name
Getting and Saving a New M-File
M-Files
Press F1
or
>> help
Existing MATLAB
Don’t do that !
>> quit
or
>> exit
Useful Commands
Command Task
>> save ‘Myprogram.m’ To save the M-file with a file name “Myprogram”
Command Task
1. Get a new script M-file and save the file with a suitable name via
menu bar.
MATLAB Fundamentals
Chapter Objectives
■ To get familiar with basic math functions and matrix manipulation functions in
MATLAB
Functions and Commands
>> date
e.g.,
>> calendar
Operators, Expressions, Statements
Function
Operator
>> Y = sin(x) + b x, b, Y
Variables
Expression
Statement
>> a= 30 <Enter>
>> name= ‘Su Su’ <Enter>
>> Y2k= 2000 <Enter>
'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
MATLAB
Operation Example
Expression
Order Operation
S= ((8*3)+5+6^2/3
Y= 3/4*5
Numbers in MATLAB
Mantissa Exponent
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Explanation Example
Expression function
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
Mathematical
MATLAB
Expression Explanation Example
function
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.)
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
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:
1 0 A {2,2}= [ 1 5 7]
A {2,1}
4 3
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
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
diag(X) Y=diag(X)
randperm(n) E=randperm(6)
randi(n) A=randi(10)
Basic Matrix Operations
Transposing:
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 = CB
A-1 *A * B = A-1 * C
I*B = A-1 *C
B = A-1 *C
1
A 1 Adj A
det A
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
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
a b c c f i
A d e f A b e h
g h i a d g
a b c g h i
A d e f A d e f
g h i a b c
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
1,1
B.C 3
a b c c b a
A d e f A f e d
g h i i h g
a b c
A d e f
g h i
Extending a Matrix
A 1 2 3 4
A 1 2 3 4 5
A 1 2 3 4 5 0 9
A(1,6)
Basic Matrix Operation (Cont.)
A 1 2 3 4
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
Mathematical MATLAB
Explanation Example
Expression function
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
Mathematical MATLAB
Explanation Example
Expression function
Mathematical MATLAB
Expression Explanation Example
function
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.
Mathematical
MATLAB
Expression Explanation Example
function
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
1
(a) (b) 2 23 (c) 1.5 104 2.5 102 ( Use double
26 precision format)
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
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
Example:
Designer 1 Designer 2
clc
clear
format bank
Area=0.5*b*h;
clc
clear
b=2;
h=3;
Design 2
Area=0.5*b*h;
display (Area)
Design Process
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
Problem:
x,y
x,y
x,y
ymax V0
0
x
Example (Projectile)
V0
t y max sin 0
g
g
y V0 t sin 0 t 2 0 < t < tymax
2
Example (Projectile)
V0= 10 m/s
Known (Input Variables)
0 = 45
x
Unknown (Output Variables)
y
Example (Projectile)
a
h A=1/2 (a+b) h
b
f(x)
a b
1. Solution
2. Solution
3. Solution
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 M-File
%%%___________________________
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
% 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
A= 30;
A=xlsread(‘Mydata',1,'A1:E5‘)
[A,B]=xlsread(‘Mydata',1,'A1:E5‘)
A=load(‘Mydata.txt’)
A=load(‘Mydata.mat’)
fscanf
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 Statement (Example)
Relational
operator x=input('Enter the value of x \n');
Condition if x<5 if x <5
end end
Flow Control or Decision (Cont.)
Relational Operators
= Equal to == if A==B
Logical Operators
| OR | if A<5 | B>2
~ NOT ~ if ~ (A>B)
Example
Relational
operator x=input('Enter the value of x \n');
if x<=5 | x>10
Logical if x <=5 | x>10
end end
Flow Control or Decision (Cont.)
Exercise
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.,
>>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
Logical Function
Logical
Example Description
Function
[1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 0]
Flow Control or Decision (Cont.)
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
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
Parking
Info Park
Leave
Password
1 25
Exercise
Nested if Statement
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.)
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.)
Find
Flow Control or Decision (Cont.)
Nested if (Example)
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.)
x
Flow Control or Decision (Cont.)
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.)
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.)
50
-50
-50 50
Flow Control or Decision (Cont.)
Elseif Clause
“elseif” is used together with “if”. It is used for checking multiple conditions.
Discrimenant
b2-4ac>0 two real numbers
b2-4ac=0 one real number
b2-4ac<0 two complex numbers
Flow Control or Decision (Cont.)
-+ ++
500
700 -- +-
200 400
50
Flow Control or Decision (Cont.)
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 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.)
Perform assigned
task
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.)
E
D
data label
IP address
Flow Control or Decision (Cont.)
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.)
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.)
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.)
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
end
Looping with For (Cont.)
Variables
1st round k=1
for k=1:1:10 Expression P(1)=2*1
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.)
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
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 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.)
y
6m
x
2 kN
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.)
X Y Classification
7 7 Bad
7 4 Bad
3 4 Good
1 4 Good
Looping with For (Cont.)
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.)
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.)
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.)
Example
Looping with For (Cont.)
While Loop
Total Balance=Save(1+0.1)
Looping with While (Cont.)
Condition clc
clear
Year=0;
while Total_Balance<=50000
Total_Balance=10000;
Year=Year+1; Save=10000;
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 )
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.)
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.)
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.)
[1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 0]
Looping with While (Cont.)
Design 2
Design 1
Looping with While (Cont.)
Parking
Info Park
Leave
Password
1 25
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
Total= 2+ 2+ 2+ 2+……..2
20
Breaking a Loop (Cont.)
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.)
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 )
Continue Command
Continue Command
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.)
elevator.
Pausing a Loop
Pause Command
end
Pausing a Loop
clc
clear
for k=1:5;
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.,
>>X=[ ]; >>display(Y)
>>disp(Y) >>display(X)
Displaying Messages and Results (Cont.)
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
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
xlswrite(‘Mydata’, X, 4, ‘A1:E5’)
e.g.,
>> X=1:100;
>> xlswrite(‘Mydata’, X, 4, ‘A1:E5’)
Saving to External Files
fid=fopen(‘filename’, ‘Mode’)
Permission
mode
>> x=0:0.1:1;
>> y= exp(x);
>>fclose(fid)
Writing format
Saving to External Files
File
Explanation
Mode
r To set the file in reading 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
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
>>fid=fopen('exp1.txt','r');
>>fprintf(fid,'%f %f\n',X);
>>fid=fopen(‘exp.txt','r');
>>A=fscanf(fid,'%f‘)
A=fscanf(file identifer,‘format’)
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
>>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
>>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
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
Wrong Spelling
>> srqt(25)
??? Undefined command/function 'srqt'.
Checking Error and Debugging
xxxxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxx
??? Error: File: Test10.m Line: 6 Column: 9
xxxxx
xxxxxxxxx Unexpected MATLAB operator.
xxxxxxxxxxxx
xxxxxxx
xxxxxxxxxxxxxxxxxx
xxxxxxxxxx
Checking Error and Debugging
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
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
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
distribution, each sensor node must be able to detect and list the partners in
C
F B D
E
G
Chapter 4
Plotting Graphs
&
Curve Fitting Toolbox
Chapter Objectives
Way 1 Way 2
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
Legend
Line plot
Axis label
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
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
Line Specifications
e.g.,
Line Specifications
b - Blue color
- - Solid line
Line Specifications
_____________
Solid line -
_
………………
Dotted line .
…
Dashed line --
. . . . .
Dash-Dot line -.
.
Creating 2D Line Graphs (Cont.)
Line Specifications
Line Specifications
. . ^
o o >
x <
+ + p
* * h
□ s
◊ d
v
Creating 2D Line Graphs (Cont.)
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 ];
>> plot (X,Y, ': s k', 'LineWidth', 2.5 ,'MarkerSize', 10, 'MarkerFaceColor','g',
'MarkerEdgeColor','r' )
Creating 2D Line Graphs (Cont.)
p ( t, ) T [ t1 t 2 t 3. ...t 24 ]
(t )
maxp ([ T ], )
t
p (t , ) e
t!
Editing Axes
Limits
X-limits Y-limits
Function Explanation
axis equal To obtain equal tick mark intervals
axis square To obtain equal length of axes
Limits
Function Explanation
To obtain equal tick mark intervals but the
axes limits the same as maximum and
axis image
minimum of data.
Limits (Example)
Write a function M-file to draw a circle with an arbitrary radius . See the
results by changing the axis styles.
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
xlabel(‘X value’)
Multiple
labels
xlabel({date;'Population';'in Years'})
ylabel(‘Y value’)
text(x,y, ‘Value’)
Font Modifiers
'FontName', 'TimesNewRoman')
Adding Legend
legend(‘toggle’)
legend(‘data1’, ‘data2’)
‘________’)
Options
Options
Vertical Horizontal
>> colorbar
North NorthOutside
South SouthOutside
East EastOutside
West WestOutside
Editing Figures (Cont.)
>> hold on
Example
>> grid on
>> grid off
Example
>> X=[0:pi/20:2*pi];
>> Y=tan(X);
>> plot (X,Y)
>> grid on
>> grid off
Editing Figures (Cont.)
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])
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.
Bar Graph
Some applications
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
Pie Chart
Some applications
Special Graphs (Cont.)
Pie Chart
>> pie(Variable);
>> pie(Variable,{‘Streing1’,‘String2’,…})
>> pie3(Variable)
>> pie(Product);
Special Graphs (Cont.)
Histogram
Frequency
Intensity
Special Graphs (Cont.)
Histogram
>> 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,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
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
Amount
1
0
time
Special Graphs (Cont.)
Stairstep Graph
Some application
Special Graphs (Cont.)
Stairstep Graph
>>stairs(X,Y)
>> t=1:10;
>> y=cos(t);
>> stairs(t,y)
Special Graphs (Cont.)
Contour Graph
Contour Graph
>>contour(X)
>> 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 ];
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.)
>> Y=sin(X);
>> Y1=2*X+2;
(2,2,2)
(2,2,[1 3])
(2,2,4)
Drawing Subplot (Cont.)
>> 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
Function Explanation
e.g.,
C= { [1,2], [6,-1], [5,7], [10,2]}
streamparticles(C)
Plotting Functions (Cont.)
>> 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.)
>> 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')
>> 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.)
comet3(X,Y,Z)
To draw animate plot >>
comet3(X,Y,Z,p)
Applications
>> cftool
Curve Fitting Toolbox (Cont.)
Eri= f(xi)-yi
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.)
Smooth No equation
Y=aebX
Non-Linear
Y=aXb
Curve Fitting Toolbox (Cont.)
Normal
Robust Bisquare
Normal
Robust Bisquare
Curve Fitting Toolbox (Cont.)
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.)
Use LS method to
Check Yes
find coefficients
convergence
of coefficients
End
Update wi No
Curve Fitting Toolbox (Cont.)
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
a b
d
>> ezellipse (12,6, x,y)
Chapter End Exercise
location (x,y).
>> 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
>> 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
>> 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=
>> 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
>> [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;
ans =
10
Symbolic Algebra
Symbolic Plot
Integrating
>>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
>> dsolve('Dy=2*x+1','x')
ans =
C15 + x*(x + 1)
Chapter 6
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
Numerical Integration
Numerical Differentiation
What is Interpolation?
x y = f(x)
3 7
5 8.1
6.5 9
x=4.2 y=?
Interpolation (Cont.)
Methods
f ( x 2 ) f ( x1 )
f ( x ) f ( x1 ) ( x x1 )
x 2 x1
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 Interpolation
x y = f(x)
9
3 7
8
7
5 8.1
6.5 9
3 5 6.5
Interpolation (Cont.)
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
b b 2 4 ac
x1 , x 2
2a
ax2+bx+c=0
C1x4+C2x3+C3x2+C4x+C5=0
Root Finding (Cont.)
MATLAB functions
>>fzero(funciton, x0)
>> solve(‘f(x)==0’)
Root Finding (Cont.)
Methods
Graphical Method
Bracketing Method
Bisection Method
Newton-Raphson Iteration
Secant Method
Root Finding (Cont.)
Graphical Method
x=[………………]
f(x)= […………….]
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.)
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.)
Guess initial xn
f( x) 0
f ( x) x x Then find xn+1
g( x ) x Reset xn=xn+1
x n 1 g( x n )
Root Finding (Cont.)
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 )
Secant Method
xn f ( xn )
x n 1 x n
f ( x n x n ) f ( x n )
f(x1,x2,x3,….xn)=0 (1)
f(x1,x2,x3,….xn)=0 (2)
f(x1,x2,x3,….xn)=0 (3)
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
Cramer’s Rule
LU Factorization
Cholesky Factorization
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.)
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];
>> 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.)
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.)
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.)
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
AX C a 11 a 12 a 13
U 0 a '22 a '23
0 0 a "33
U L
1 0 0
LD C L f 21 1 0
f 31 f 32 1
UX 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)
>> A=
>>X=inv(U)*D
Solutions of Linear Equations (Cont.)
Cholesky Factorization
a 11 a 12 a 13 UT [ 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.)
>> 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 (nk)
a nn
Solutions of Linear Equations (Cont.)
x i x i (1 )x i 1
= 1 ~ 2
Solutions of Linear Equations (Cont.)
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.)
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
>>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
>>integral2(F,Lx,Ux,Ly,Uy)
>>integral3(F,Lx,Ux,Ly,Uy, Lz,Uz)
Methods
Trapezoidal Rule
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.)
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.)
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.)
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.)
>>quad2d(F,Lx,Ux,Ly,Uy)
>>quadgk(F,L,U)
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.)
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.)
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)
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 2x difference
Numerical Differentiation (Cont.)
f f
? ?
x y
2f 2f
? ?
x 2
y 2
2f
?
xy
Numerical Differentiation (Cont.)
f ( x ) sin( 2x )
f ( x )
2 cos( 2x ) 1.1774
x
Numerical Differentiation (Cont.)
>>gradient(A,x)
>> f f ( x i 1 ) f ( x i 1 )
x 2x
Numerical Integration of ODE
dy
y' f ( y , t ) Initial Value Problem
dt
y y' ? y' f ( y , t )
y( 0 ) C
Numerical Integration of ODE (Cont.)
>> dsolve('Dy=2*x+1','x')
ans =
C15 + x*(x + 1)
Numerical Integration of ODE (Cont.)
>> 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
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.)
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.)
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
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 'i1/ 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.)
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.)
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.)
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.)
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)
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.)
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.)
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.)
>> [t,x]=ode45(dxdt,[0:4],0)
>> [t,v]=ode45(dvdt,[0:4],0)
Numerical Integration of ODE (Cont.)
y=F(a)+F(b);
end
>>test(@sin,2,3)
Numerical Integration of ODE (Cont.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
z (0)= ?
T=200
d2T
2
h ( T T ) 0
dx
dT
z
dx x=0 x=L
Purposes of GUIs
same panel
GUIs in MATLAB (Cont.)
Application of GUIs
simulation in
GUI files
GUI
Step 1
Step 3
Step 2
>>guide
GUI component
panel
Drag here
Property inspector
GUIs in MATLAB (Cont.)
GUI Components
Push Slide
Toggle Table
Button
Radio
Check Figure
Button Panel
Peak Time
Plot
GUI Components
Push Button
Push Button
GUI Components (Cont.)
Push Button
Push button
Slider
Slider
GUI Components (Cont.)
Slider
Slider
handles.step=get(hObject,'Value')
guidata(hObject, handles);
GUI Components (Cont.)
Radio Button
Radio button
GUI Components (Cont.)
Radio Button
Radio button
handles.H=get(hObject,‘Value');
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Panel
GUIs in MATLAB (Cont.)
Panel
handles.H=get(hObject,‘Value');
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Check Box
GUIs in MATLAB (Cont.)
Check Box
handles.H=get(hObject,‘String')
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Editable text
GUIs in MATLAB (Cont.)
Editable text
handles.H=get(hObject,'String‘)
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Editable text
handles.H=eval(get(hObject,'string'))
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Static text
GUIs in MATLAB (Cont.)
Pop-up Menu
GUIs in MATLAB (Cont.)
Pup-up Menu
handles,H= get(hObject,'Value')
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
List box
GUIs in MATLAB (Cont.)
List box
handles,H= get(hObject,'Value')
guidata(hObject,handles)
GUIs in MATLAB (Cont.)
Toggle button
GUIs in MATLAB (Cont.)
Toggle button
Axes
Chapter 7
>> Ccoder
Project name
Configuration of Ccoder
Ccoder (Cont.)
Building C Code
Ccoder (Cont.)
Only for inter operation, floating point operation will not appear
Comment style
Overall
setting
Sound Recording
y = getaudiodata(recorder, dataType)
Thank You
19/6/2015