You are on page 1of 314

2

MATLAB
3

GUI
text
MATLAB MATLAB 5.3
Release 11 MATLAB MATLAB 6.0 Release 12 MATLAB

GUI
MATLAB 6.0 GUIDE
GUI
GUI GUIDE
1
MATLAB MATLAB
MALLAB Desktop
Cell Array Structure 2
version 5.0
12 15
GUI MATLAB Visual MATLAB
Graphic MATLAB 12 object MATLAB
13 Object 14 GUIDE
GUI 15 GUI

1 MATLAB _________________________________________1
1.1 ______________________________________________________________ 1
1.2 MATLAB ________________________________ 3
1.3 MATLAB___________________________________________________ 6
1.4 _________________________________________________________ 14
1.5 _______________________________________________________________ 19

2 MATLAB ________________________________________20
2.1 Scalars, Vectors and Matrices _______________________________________ 20
2.2 Matrix Operation_______________________________________________________ 27
2.3 Matrix Functions _______________________________________________________ 29
2.4 Multidimensional Arrays__________________________________________________ 37
2.5 Cell Arrays ___________________________________________________________ 39
2.6 Structures ___________________________________________________________ 43
2.7 Output Options ________________________________________________________ 45
2.8 Simple Plot __________________________________________________________ 47
" ________________________________________________ 57

3 MATLAB FUNCTIONS __________________________________________62


3.1 _________________________________________________________ 62
3.2 ______________________________________________________ 63
3.3 Hyperbolic Functions ____________________________________________________ 63
3.4 Complex Number Functions _______________________________________________ 64
3.5 Polynomial Functions____________________________________________________ 65
3.6 Statistical and Logical Functions ___________________________________________ 67
3.7 File Input/Output Functions _______________________________________________ 71
" ________________________________________________ 76
4 M-FILE ______________________________________________79
4.1 M-File_______________________________________________________________ 79
4.2 Script Files & Function Files _______________________________________________ 80
4.3 M-File ___________________________________ 83

5 SOLUTION TO SYSTEM OF LINEAR EQUATIONS ________________________89


5.1 ____________________________________________ 89
5.2 Inverse ___________________________________________ 90
5.3 Matrix ___________________________________________ 91
5.4 Eigenvalues Eigenvectors _____________________________________________ 92
" ________________________________________________ 94

6 INTERPOLATION CURVE FITTING _______________________________98


6.1 Interpolation Curve Fitting _______________________________________ 98
6.2 Interpolation __________________________________________________________ 99
6.3 Polynomial Curve Fitting_________________________________________________ 104
" _______________________________________________ 106

7 NUMERICAL INTEGRATION AND DIFFERENTIATION _____________________110


7.1 Numerical Integration ___________________________________________________ 110
7.2 Integrate Double Integral _____________________________________________ 112
7.3 Numerical Differentiation ________________________________________________ 114
" _______________________________________________ 115

8 SOLUTION OF ORDINARY DIFFERENTIIAL EQUATIONS ___________________118


8.1 First Order ODE _______________________________________________________ 118
8.2 Higher Order ODE _____________________________________________________ 120
8.3 Boundary Value Problems : Shooting Method __________________________________ 123
" ______________________________________________ 129
9 MATLAB GRAPHICS __________________________________________134
9.1 plot 2 _____________________________________________________ 134
9.2 3 _________________________________________________ 141
9.3 _________________________________________________ 151
9.4 ________________________________________________ 153
" ______________________________________________ 155

10 SYMBOLIC MATHEMATICS_____________________________________160
10.1 Symbolic Algebra ____________________________________________________ 160
10.2 Equation Solving _____________________________________________________ 165
10.3 Differentiation Integration___________________________________________ 168
10.4 Symbolic Transformation_______________________________________________ 170
10.5 Function Calculator ___________________________________________________ 173
10.6 Symbolic Math Toolbox : Student Edition ____________________________ 177

11 M-BOOK__________________________________________________180
11.1 M-book _____________________________________________________ 180
11.2 ___________________________________________________ 181
11.3 Input & Output Cells __________________________________________________ 182
11.4 Notebook Menu ___________________________________________ 187
11.5 M-book Template ______________________________ 188

12 Handle Graphic _____________________________________________190


12.1 MATLAB Graphic Object _______________________________________________ 191
12.2 Create Object Function ________________________________________________ 193
12.3 Basic Graphic Object Properties__________________________________________ 195
12.4 GET and SET Function _________________________________________________ 198
12.5 Related Object Function _______________________________________________ 205
13 Object Property_____________________________________________211
13.1 Figure_____________________________________________________________ 212
13.2 Axes______________________________________________________________ 218
13.3 Uicontrol ___________________________________________________________ 229
13.4 Uimenu ____________________________________________________________ 237
13.5 Uicontextmenu ______________________________________________________ 240

14 GUIDE________________________________________243
14.1 GUI GUIDE________________________________________________ 243
14.2 GUI MATLAB _________________________________________ 244
14.3 Application M-file GUIDE______________________________________ 248
14.4 _______________________________ 256
14.5 User Interface Controls ________________________________________________ 262
14.6 Understanding the Application M-File ______________________________________ 262
14.7 GUI__________________________________________ 267
14.8 GUI ____________________________________________ 269
14.9 ________________________________________________________ 270

15 GUIDE ____________________________________________271
15.1 Radio Button _____________________________________________ 271
15.2 Slider Editable Text __________________________________________ 279
15.3 Check Box, List Box Popup Menu _______________________________ 282
15.4 Object Handle GUI _______________________________ 287

MATLAB________________________________________________ 295
____________________________________________________________ 306
1 MATLAB

1.1
MATLAB MATLAB


MATLAB

MATLAB (Interactive)
MATLAB
MATLAB
array (
element ) array MATLAB dimension

matrix vector
C Fortran
MATLAB
MATLAB MATrix LABoratory MATLAB
Matrix MATLAB
Dr. Cleve Molor Fortran
LINPACK EISPACK
MATLAB C MathWorks
LAPACK ARPACK

MATLAB
matrix
..2000 MATLAB 6.0

Introduction to MATLAB 1
12 MATLAB

MATLAB
C Fortran
MATLAB

MATLAB MathWorks MATLAB
toolbox MATLAB
Toolbox
MATLAB
toolbox
signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation
MATLAB

 MATLAB
Math Works High-Performance
Numeric Computation and Visualization Software
 MATLAB

 MATLAB function
function function

 MATLAB

C, FORTRAN
 MATLAB 2 3

 MATLAB Dynamic Link Word, Excel

windows
 MATLAB toolbox function


MATLAB

2 Basic Operation
MATLAB



MATLAB MATLAB

 MATLAB

 Help MATLAB

 Internet

http://www.mathworks.com

1.2 MATLAB
n MATLAB
MATLAB MATLAB
5
1. Development Environment.

2. The MATLAB Mathematical Function Library.

3. The MATLAB Language.

4. Handle Graphics

5. The MATLAB Application Program Interface (API)

Development Environment

graphical user interface MATLAB Desktop Command
Windows, command history browsers help, workspace, files search path

Introduction to MATLAB 3
The MATLAB Mathematical Function Library

Algorithms
sine, cosine
inverse matrix eigenvalues eigenvector
fast Fourier transforms

The MATLAB Language


matrix array
input
output Matlab

Handle Graphics

image processing

Graphic User Interface MATLAB

The MATLAB Application Program Interface (API)


library C Fortran
MATLAB
MATLAB (dynamic linking), MATLAB engine
MAT-file

o MATLAB
Windows
MATLAB shortcut MATLAB desktop
Start MATLAB
Programs Windows

4 Basic Operation
MATLAB 6 MATLAB desktop

MATLAB MATLAB
desktop

Launch Pad
toolbox MATLAB
desktop
desktop (docking)
desktop desktop shortcut
context menus desktop
Preferences File Command
Window desktop Help
Preferences

Introduction to MATLAB 5
1.3 MATLAB
MATLAB 6.0 Version MATLAB
MATLAB desktop
version 6 MATLAB
MATLAB
desktop MATLAB 6

MATLAB Desktop 5 Command Windows,
Command History Window, Current Directory Browser, Workspace Browser Launch Pad

n Command Window
Command Window MATLAB
version MATLAB
MATLAB

MATLAB Command Window MATLAB


MATLAB MATLAB MATLAB
prompt Professional Edition EDU Student Edition
MATLAB
EDU
file
MATLAB M-file

6 Basic Operation
Command History
MATLAB
-


(Delete Selection) (Delete to Selection)
(Delete Entire History)
Command Windows
M-file
Shift
Create M-File Editor M-file
M-file

o Current Directory Browser


MATLAB MATLAB Current Directory Search Path

MATLAB file
M-file
Current Directory Search Path

Introduction to MATLAB 7
Current Directory
Current Directory Desktop Toolbar
Current Directory

Current Directory
directory Current Directory
Current Directory directory Browser
directory file
Windows
file
MATLAB Current Directory Browser desktop tool current
Directory Browser

Current Directory Browser file


file file
help M-file
Windows

8 Basic Operation
Search Part
Command Window Function
Search Path Search Path
directory MATLAB directory MATLAB
MATLAB Toolbox Search Path
Search Path Set Path
File Menu directory Search Path
directory Search Path path
MATLAB Command Prompt
path

MATLABPATH
C:\MATLABR12\toolbox\MATLAB\general
C:\MATLABR12\toolbox\MATLAB\ops
..
C:\MATLABR12\toolbox\wavelet\wavedemo
C:\MATLABR12\toolbox\rtw\targets\xpc\target\kernel\embedded
C:\MATLABR12\work

Search Part MATLAB


addpath Search Path rmpath directory Search Path

p Workspace Browser
MATLAB
(Workspace) MATLAB
M-file load
MATLAB 6.0 Workspace Browser
Desktop Tool version MATLAB who whos
Command Windows Workspace Browser

Introduction to MATLAB 9
Workspace Browser array workspace


workspace Browser Workspace
 Delete Selection

array
( )
cell cell

 Open Selection


Array Editor
space sheet Matrix Matrix
array editor

10 Basic Operation
Array Editor ()
cell cell Array Editor

array size
cell
undo

q Launch Pad
Launch Pad toolbox
MATLAB Toolbox
Launch Pad file Windows Explorer
Toolbox

Launch Pad

Introduction to MATLAB 11
5 MATLAB Desktop
Desktop undock
(Command Windows)
Desktop Dock View
desktop
Desktop
View

Desktop Preference File

r Editor/Debugger
M-file Text Editor Notepad
M-file ASCII Code MATLAB
version 5 editor MATLAB
editor debugger
Editor/Debugger M-files
MATLAB Editor/Debugger text
editor Debugger
MATLAB

12 Basic Operation
MATLAB file M-file
Editor/Debugger

Editor/Debugger
Editor/Debugger
M-file

s Graphic Windows
MATLAB Graphic Windows
Graphic Window
MATLAB Menu Bar Graphic Window

Introduction to MATLAB 13
Graphical User
Interface
windows Graphic Window
version MATLAB
Graphic Window
version 6
fit curve Graphic Window
Graphic Window Graphic

1.4
MATLAB

MATLAB
MATLAB Command Window
MATLAB

14 Basic Operation
MATLAB

 Angsana New Thai


 input MATLAB Courier New


Airtime = B*C(1,2)
 output MATLAB Courier New
Airtime = 20
 % comment MATLAB


 ^ MATLAB
 Enter key ( Enter
key )

o MATLAB

 quit exit MATLAB

 clc Command Window

 clf Graphic Window

 clear

 save disk

 MATLAB

Ctrl c

^ MATLAB function

p Function Keys
MATLAB keys

Introduction to MATLAB 15
Ctrl-p
Ctrl-n
Ctrl-f 1
Ctrl-b 1
Del Backspace 1
Ctrl-l Ctrl- 1
Ctrl-r Ctrl- 1
Ctrl-a Home
End
Ctrl-k

q
MATLAB
help

 help MATLAB function help


 help function MATLAB function
 MATLAB demo
 help Menu bar
 Help Windows helpwin

version Help Browser MATLAB


MATLAB MathWorks Help
Browser MATLAB Desktop Web Browser
HTML Help Browser Web Browser
Help Browser

16 Basic Operation
Help Help Browser
MATLAB Help
html Browser
( install ) Help browser
help

r Using MATLAB
 Development Environment MATLAB desktop
 Mathematics
MATLAB
 Programming and Data Types MATLAB
 Graphics
MATLAB
 3-D Visualization view lighting
3

Introduction to MATLAB 17
 External Interfaces/API C
Fortran Java, , serial port I/O, ActiveX DDE
 Creating Graphical User Interfaces
MATLAB graphical user interface

s Reference
 MATLAB Function Reference MATLAB
syntax
Function
By Category Alphabetical List of Functions

 External Interfaces/API Reference MATLAB



MATLAB

t MATLAB Demos
Toolbox
MATLAB
MATLAB
demo

demo

Run. MATLAB

18 Basic Operation
1.5
MATLAB

3 MATLAB

MATLAB MATLAB 6

Introduction to MATLAB 19
2 MATLAB

2.1 Scalars, Vectors and Matrices



scalar vector matrix
MATLAB matrix
scalar matrix [1 x 1]

vector row matrix [ n x 1] column matrix [1 x n]

row vector column vector

MATLAB

underscore ( _ )

MATLAB

19
MATLAB case-sensitive variable

xA, xa, XA

n
assignment statement =


A 1
A = 1

20 Basic Operation
vector matrix [ ]
(row) elements row
(space) comma
A = [1, 2, 3]
A = [1 2 3]

MATLAB

A =

1 23

matrix A 1 row x 3 column


1 2
sami-colon row matrix a=
3 4

a = [1 2;3 4]
a =
1 2
3 4

row
enter
a =[1, 2
3, 4]

row ellipsis comma


3
a = [1, 2, 3,...
4 ,5, 6]

a matrix [1 x 6]

MATLAB matrix matrix


a = [1 2 3]
b = [0 a]

Basic Operation 21
b b = [0 1 2 3]

MATLAB (echo)

a = [1, 2, 3]

MATLAB
a =
1 2 3
MATLAB semi-
colon
a = [1, 2, 3];

echo
MATLAB ans

0 MATLAB
echo echo

element matrix index


a = [1, 2; 3, 4]
row 1 column 2 2 5
a(1,2) = 5

matrix a
a =
1 5
3 4

matrix single row single column matrix index matrix


a = [1 2 3]


a(3) = 5

a
a = [1 2 5]

22 Basic Operation
a = [1 2 3] a(7) = 5 a
a = [1 2 0 0 0 0 5]

MATLAB element 3 7 element


MATLAB 3
who
whos , byte


size matrix array a = 13 2
4
,

size(a)
ans =
2 2

o Colon operator
Colon operator operator matrix

vector matrix

x = [1 2 3; 4 5 6; 9 10 0];

a column 1 x
a = x(:, 1)
a =
1
4
9

b = x(2,:) b row 2 x
b = [4 5 6]

Colon operator matrix colon 2



k = 1:5 k row vector

k = [1, 2, 3, 4, 5]

Basic Operation 23
colon 3 2
3
k = 1:0.5:5 row vector
k = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
colon
k = 5:-0.5:1
k = [5, 4.5, 4, 3.5, 3, 2.5, 2, 1.5, 1]

colon operator submatrix


1 2 3
a = 4 5 6
9 7 8

a=[1 2 3;4 5 6;9 7 8]


a =
1 2 3
4 5 6
9 7 8
minor a(1, 1) row 1 column 1
b = a(2:3,2:3);

b row 2 row 3 column 2 column 3 a

c = a(1:2,1)
c =
1
4

d = a(:,2:3)
d =
2 3
5 6
7 8

a(:) matrix column column 1 a column 2, 3...



e = a(:)
e =
1
4
9
2
5
7
3

24 Basic Operation
6
8

Matrix matrix 0 x 0 a = [ ]; b = 10:1:0; matrix


matrix element

Transpose Matrix row column column row

1 4
1 2 3
a= a = 2 5
T

4 5 6 3 6

MATLAB transpose ( ' ) a'


a = [1 2 3;4 5 6]
a =
1 2 3
4 5 6

b = a'
b =
1 4
2 5
3 6

p
1 1
a = [1 2 3];
a = [3 4];

MATLAB a = [3 4]

a = [1 2 3];
a = [5 a];

MATLAB
A = [5 1 2 3];

q MATLAB
MATLAB

pi 3.14159
i j imaginary valve 1

Basic Operation 25
Inf infinity
NaN Not-a-Number (undefined) 0 0
clock Computer

date format -- 1-jan-97
eps floating-point precision computer
ans

r Matrix MATLAB
Matrix MATLAB matrix

rand(m,n) matrix [m x n] element


0 1
rand(m) square matrix
hilb(N) Hilbert matrix matrix [N x N] element
1
(i + j 1)
magic(N) square matrix [N x N] 1 N2
element row, column diagonal
N 1, 3, 4, 5,
zeros(m,n) matrix [m x n] element
ones(m,n) matrix [m x n] element 1
eye(m,n) matrix [m x n] element diagonal 1
matrix square matrix
linspace(a,b,n)
row vector 1 x n a
b n n
MATLAB n 100
logspace(a,b,n)
row vector 1 x n a
b logarithmic n n
MATLAB n 100

26 Basic Operation
square matrix m n

ones(2) matrix 11 1
1


a=eye(3,4)
a =
1 0 0 0
0 1 0 0
0 0 1 0

linspace(1,3,10)
ans =
Columns 1 through 7
1.0000 1.2222 1.4444 1.6667 1.8889 2.1111 2.3333
Columns 8 through 10
2.5556 2.7778 3.0000

s String Variable

string
quotation '
Str1='Tom';
Str2='Pookie';

string
function
matrix element string
matrix column
row blank space string

2.2 Matrix Operation


n Dot Product
Dot Product inner product scalar value vector
A B vector
N
A B = a b N element A B
i =1
i i

A = [1 2 3] B = [4 5 6] C = AB (1)(4) + (2)(5) + (3)(6) = 4+10+18 =


32
MATLAB
C = dot(A,B)

Basic Operation 27
dot(A,B) dot product A B A B matrix dot product row
vector element column dot product column A
B

A=[1 2 3];B=[4 5 6];

dot(A,B)
ans =
32

o Matrix
Matrix A B matrix column row
matrix row column A
[m x n] B [p x q] AB n = p matrix m x q
AB BA matrix MATLAB C = AB
C =A *B

column A row B MATLAB

p Matrix Scalar
matrix scalar element matrix A=[1 2];

C =2*A
C =
2 4

q - Matrix
matrix / //
element matrix

A=[1 2 3];
B=[4 5 6];
C=A-B
C =
-3 -3 -3

r Matrix
Matrix square matrix

28 Basic Operation
A2 = AA

MATLAB A2 A^2

A^2 A*A

A^3 A*A*A

s Matrix Polynomial
polynomial function x

f ( x ) = a n x n + a n 1 x n 1 +... a1 x + a 0

an , an1 ,... polynomial x matrix matrix polynomial


matrix matrix MATLAB polynomial
matrix function polyvalm
polyvalm (a,x) polynomial matrix x a x
square matrix a row vector

operation Matrix
MATLAB operation Matrix
operation elements

2.3 Matrix Functions


n Matrix Inverse
A square matrix Inverse Matrix A A-1

AA 1 = A 1 A = I

I identity matrix matrix inverse matrix singular matrix


matrix inverse nonsingular matrix inverse matrix

MATLAB inv

Basic Operation 29
inv(a) inverse matrix a a singular matrix matrix
inverse MATLAB

A=[1 4;8 9];


inv(A)
ans =
-0.3913 0.1739
0.3478 -0.0435

o Rank of Matrix
row matrix rank matrix

1 2 3
a=
2 4 6

row 2 2 row row a rank 1


matrix rank row singular matrix MATLAB rank
rank
rank(a) rank matrix a

a=[1 2 3;2 4 6];


rank(a)
ans =
1

p Determinant of Matrix
Determinant square matrix scalar matrix determinant
square matrix a MATLAB
det(a) determinant a

matrix determinate matrix singular matrix determinant MATLAB

a=[1 2 3; 2 7 6; 5 4 8];
det(a)
ans =
-21

q Matrix

30 Basic Operation
matrix MATLAB function
linear equations
Ax = B

x= A B 1

MATLAB x=A\B
A\B = A-1B

xA = B
x = BA-1
MATLAB B/A
B/A = BA-1
/ MATLAB left matrix division

\ MATLAB right matrix division

x MATLAB Gauss elimination numerical


Technique

r Matrix Decomposition
matrix A matrix 2 matrix
Decomposition Factorization matrix matrix
decomposed matrix 3

c LU-decomposition Triangular Factorization matrix


matrix lower triangular matrix upper triangular matrix
Lower Triangular matrix, L, matrix elements main diagonal
( main diagonal)

1 0 0
L = 4 2 0
5 6 3

Basic Operation 31
Upper Triangular matrix, U matrix elements main diagonal
( main diagonal)

1 2 3
U = 0 4 5
0 0 6

A matrix
A = LU
MATLAB

[L,U]= lu(A) matrix A Lower triangular L


upper triangular U LU = A Matrix A Square
Matrix

A=[1 3 2;-2 6 1;2 5 7];
[L,U]=lu(A)
LD =
-0.5000 0 1.0000
1.0000 0 0
-1.0000 1.0000 0

UD =
-2.0000 -6.0000 1.0000
0 -1.0000 8.0000
0 0 2.5000

0 LU-decomposition
LU-decomposition permutes lower
triangular factor

permuted lower triangular factor


[L,U,P]= lu(A)
L =
1.0000 0 0
-1.0000 1.0000 0
-0.5000 0 1.0000
U =
-2.0000 -6.0000 1.0000
0 -1.0000 8.0000
0 0 2.5000
P =
0 1 0
0 0 1
1 0 0

32 Basic Operation
PA = LU

d QR-Decomposition matrix orthonormal matrix Q upper


triangular matrix, R ( right hand matrix main diagonal
) orthogonal matrix matrix

QQ T = I

Q 1 = Q T

MATLAB
[Q,R]= qr(A) matrix Q R A = QR Q orthonormal
R upper triangular matrix A Square
Matrix

A=[1 2 3; 5 8 7];
[Q,R]=qr(A)
Q =
-0.1961 -0.9806
-0.9806 0.1961

R =
-5.0990 -8.2369 -7.4524
0 -0.3922 -1.5689

e Singular Value decomposition (SVD) decomposed matrix matrix 3


matrix
A = QSV

Q V orthonormal matrix S diagonal matrix MATLAB


[Q,S,V]=svd(A) decompose A A = QSV Q V orthonormal
s diagonal matrix

0 decompose 3 A [m x n]
U, L R A

Q m x m
V n x n
S m x n

Basic Operation 33

A=[1 4;8 9];
[L,U]=lu(A)
L =
0.1250 1.0000
1.0000 0
U =
8.0000 9.0000
0 2.8750
[Q,R]=qr(A)
Q =
-0.1240 -0.9923
-0.9923 0.1240
R =
-8.0623 -9.4266
0 -2.8528
[Q,S,V] = svd(A)
Q =
0.2966 0.9550
0.9550 -0.2966
S =
12.5963 0
0 1.8259
V =
0.6301 -0.7765
0.7765 0.6301

s Array Operation
element matrix
element - by - element operation array operation
A = [1 2 3 4];
B = [2 4 4 5];

A * B matrix C c i = ai bi

c (1) = A(1) * B(1) , c ( 2) = A( 2) * B( 2) ,...

array operation . *
C = A.*B

D element clement element A


B . /
D = A./B

E = A.^B

34 Basic Operation
E element element A element B

A=[1 2 3 4 5];
B=[4 5 9 10 2];
A.*B
ans =
4 10 27 40 10
B.^A
ans =
4 25 729 10000 32

0 Array operation matrix matrix

t
MATLAB
(1)
(2)
(2)
(3)

u Matrix
matrix
MATLAB function
rot90(A) matrix A 90
rot90(A,n) matrix A 90 n
fliplr(A) Matrix A column

flipud(A) Matrix A row

reshape(A,m,n) matrix A [m x n] element matrix A
mn MATLAB
column A

Basic Operation 35
diag(x) x matrix vector main diagonal x
element x vector matrix vector A diagonal
triu(A) square matrix matrix A main diagonal
A
triu(A,k) square matrix matrix A diagonal k
A
tril(A) square matrix matrix A main diagonal
A
tril(A,k) square matrix matrix A diagonal k
A

A=[1 2 3;0 2 4;3 6 8]


A =
1 2 3
0 2 4
3 6 8

rot90(A)
ans =
3 4 8
2 2 6
1 0 3

tril(A)
ans =
1 0 0
0 2 0
3 6 8

triu(A,2)
ans =
0 0 3
0 0 0
0 0 0

diag(A)
ans =
1
2
8
flipud(A)
ans =
3 6 8
0 2 4
1 2 3

36 Basic Operation
2.4 Multidimensional Arrays
MATLAB 2 MATLAB
version 5 2 Matrix 2

x=[1 3 5; 4 2 8]
x =
1 3 5
4 2 8

y=[7 1 4;2 0 1]
y =
7 1 4
2 0 1

z=[4 2 1;3 6 9]
z =
4 2 1
3 6 9

3 3
3 x, y,
z
row column

(concatenates) cat
d=cat(3,x,y,z)
d(:,:,1)=
135
428
d(:,:,2)=
714
201
d(:,:,3)=
4 2 1
3 6 9

size(d)
ans =
2 3 3

x, y, z 2 x 3 d 2 x 3 x 3 cat

Cat(dims,A1,A2,A3,...)

Basic Operation 37
matrix A1, A2, A3,... matrix
dims matrix
Multi-dimensional Array

ndim(A) dimension A
B = permute(A,order) A B order
order vector B
element
ipermute(A,order) permute(A, order)
shiftdim(A,n) dimension A n
B = squeeze(A) dimension 1 B element
A 1
matrix vector
vector

x=[1 3 5;4 2 8];


y=[7 1 4;2 0 1];
z=[4 2 1;3 6 9];
d=cat(3,x,y,z);
e = permute(d,[3 1 2])
e(:,:,1) =
1 4
7 2
4 3
e(:,:,2) =
3 2
1 0
2 6
e(:,:,3) =
5 8
4 1
1 9
f = ipermute(e,[3 1 2])
f(:,:,1) =
1 3 5
4 2 8
f(:,:,2) =
7 1 4
2 0 1
f(:,:,3) =
4 2 1
3 6 9
g=shiftdim(d,2)

g(:,:,1) =
1 4
7 2

38 Basic Operation
4 3
g(:,:,2) =
3 2
1 0
2 6
g(:,:,3) =
5 8
4 1
1 9
p=rand(2,1,4,3);
size(p)
ans =
2 1 4 3
p=squeeze(p);
size(p)
ans =
2 4 3


1-1-3 g
g(1,1,3)
ans =
5

2.5 Cell Arrays


MATLAB 5 cell array version
element matrix cell
array element matrix matrix

n Cell Arrays
cell arrays { } 2
cell index
x(1,1)={[1 2;3 4]};
x(1,2)={5};
x(2,1)={linspace(0,10,10)};
x(2,2)={'Text Only'};

content addressing
x{1,1}=[1 2;3 4];
x{1,2}=5;
x{2,1}=linspace(0,10,10);
x{2,2}='Text Only';


matrix x 2 x 2 element cell x(1,1) matrix 2
x 2 x

Basic Operation 39
x
x =
[2x2 double] [ 5]
[1x10 double] 'Text Only'

size(x)
ans =
2 2

x
class(x)
ans =
cell

x cell arrays x celldisp


celldisp(x)
x{1,1} =
1 2
3 4
x{2,1} =
Columns 1 through 7
0 1.1111 2.2222 3.3333 4.4444 5.5556 6.6667
Columns 8 through 10
7.7778 8.8889 10.0000
x{1,2} =
5
x{2,2} =
Text Only

cell
x{1,2}
ans =
5

cell array matrix


column ;
y={[1 3; 5 6], [2 3; 5 7]; ['TOM';'TON'],[2+i 5+4i]}
y =
[2x2 double] [2x2 double]
[2x3 char ] [1x2 double]

cell array cell


Z=cell(2,2)
z =
[] []
[] []

o Cell Array

40 Basic Operation
cell array matrix

x
x =
[2x2 double] [ 5]
[1x10 double] 'Text Only'

y
y =
[2x2 double] [2x2 double]
[2x3 char ] [1x2 double]

a=[x y]
a =
[2x2 double] [ 5] [2x2 double] [2x2 double]
[1x10 double] 'Text Only' [2x3 char ] [1x2 double]

b=[x;y]
b =
[2x2 double] [ 5]
[1x10 double] 'Text Only'
[2x2 double] [2x2 double]
[2x3 char ] [1x2 double]

matrix colon operator


c=b(2:3,1)
c =
[1x10 double]
[2x2 double]

reshape
c=reshape(b,2,4)
c =
[2x2 double] [2x2 double] [ 5] [2x2 double]
[1x10 double] [2x3 char ] 'Text Only' [1x2 double]

cell array

cell cell

cell matrix cell
matrix
deal

Basic Operation 41

c
c =
[2x2 double] [2x2 double] [ 5] [2x2 double]
[1x10 double] [2x3 char ] 'Text Only' [1x2 double]

c{1,4}
ans =
2 3
5 7

c{1,4}(2,1)
ans =
5

[p q] = deal(c{1,2:3})
p =
1 3
5 6
q =
5

p Cell Array Character String


character string matrix
column
MATLAB 5.x cell arrays character string
column cell
x={'Tom';'Pookie';'Tata';'Nut';'Christina';'Mai'}
x =
'Tom'
'Pookie'
'Tata'
'Nut'
'Christina'
'Mai'

class(x)
ans =
cell

size(x)
ans =
6 1

x cell array 6 row x 1 column row


42 Basic Operation
2.6 Structures
3 MATLAB 5.x
structure MATLAB structure object (Data
Containers) fields (database)
structure

n Structure
MATLAB 5.x


field
field


part (name) (make)
(price) (remark) filed 4 field
field field
Parts.name ='Left motor';
Parts.make='GE';
Parts.price=3990;
Parts.remark='Re-build';

parts
parts =
name: 'Left motor'
make: 'GE'
price: 3990
remark: 'Re-build'

2
parts(2).name='Over head cam';
parts(2).make='ACME';
parts(2).price=420;
parts(2).remark='New';


parts

Basic Operation 43
parts =
1X2 struct array with fields:
name
make
price
remark

1 MATLAB
field
parts.name
ans =
Left motor
ans =
Over head cam

Parts(2).price
ans =
420

field
total = parts(1).price*35.4
total =
141246

o field
program
MATLAB 5.x

field object , matrix, cell array


Structure
field fieldname
fieldnames(parts)
ans =
'make'
'name'
'price'
'remark'

structure struct
parts=struct('name',N,'make',M,'price',P)
parts =
1x2 struct array with fields:
name
make

44 Basic Operation
price

matrix N, M ,P

field sub-field
parts.make.FirstChoice='GE';
parts.make.SecondChoice='PW';

file field make field structure

parts
parts =
make:[1x1 struct]

getfield
F=getfield(S,'field')
F field F =
S S 1-by-1 structure.
F=getfield(S,{i,j},'field',{k})
F = S(i,j).field(k).

MATLAB 5.x MATLAB


2.7 Output Options



MATLAB Command Window Enter Key MATLAB

n Display Format

MATLAB
format short 4 22.1234

Basic Operation 45
format long 15 22.123456789012345

format bank 2 22.12

format short e 4 10 2.123 e+01

format long e 15 10 2.12345678901234 e+01

format + + , - +

format short MATLAB



format short
pi
ans =
3.1416

format long
pi
ans =
3.14159265358979

format short e
pi
ans =
3.1416e+000

format long e
pi
ans =
3.141592653589793e+000

o
MATLAB echo
MATLAB

disp
A disp(A) A disp(Display)
MATLAB Display (string)

A=10;
disp(A) ; disp(newtons)
10

46 Basic Operation
newtons


fprintf output
disp fprintf output variable
(specifier) %e, %f %g
%e exponential notation 2.3456 + 2
%f
%g %e %f
specifier %6.2f 4 2
1
fprintf
A=10;
fprintf (Total force is %f newtons \n,A)
Total force is 10.000000 newtons

\n
fprintf (Total force is \n %f newtons \n,A)
Total force is
10.000000 newtons

fprintf (Total force is %6.2f newtons \n,A)


Total force is 10.00 newtons

2.8 Simple Plot



MATLAB 2
3 3
x-y

MATLAB plot
plot
plot(x,y) Linear plot x y x y
semilogx(x,y) plot x y x log y

semilogy(x,y) plot x y x y log


loglog(x,y) plot log scale x y
plotyy(x1,y1,x2,y2)

Basic Operation 47
Linear plot x1-y1 x2-y2 y
y1 y2 x

plot MATLAB graphic window
plot plot graphic window plot
figure Command Window File menu New Figure
graphic windows figure 1, figure 2, ..

n
plot ( plot
semilogx,... )
plot(x,y) Plot vector x vector y coordinate (xj , yj)
plot(y) Plot coordinate ( j, yj ) vector y
plot(z) complex number z = x + iy plot coordinate (Re(z), Im(z))
plot(A) A matrix plot coordinate (j,A1j), (j,A2j),.. j index
row plot A column index
plot(x,A) Plot matrix A m x n vector x x vector m
plot column A x vector x n
plot row A x
plot(A,x) plot vector x Matrix A A m x n vector x m
plot x column A vector x n plot x
row A
plot(A,B) plot column B column A A B m x n
plot curve n m coordinate
plot(x,y,str)
str character string


y = yellow . -
g = green * --
m = magenta X -. dash-dotted

48 Basic Operation
b = blue O : dotted
c = cyan +
w = white S
r = read D
k = black ^
V
>
<
P
H

MATLAB - ()
MATLAB y, g, m, ... plot string
r+ plot +
plot(x,y,str1,w,v,str2,...)
plot curve 1
plot(xi, yi) str1 plot (wi ,vi) str2
str MATLAB y, g, m ...

a = plot(x,y,str1,w,v,str2,...)
plot curve MATLAB a
plot (MATLAB
handle ) MATLAB

o Graphics Window
Graphics window
character string txt ='charactor string
'

title(txt) string txt


xlabel(txt) string txt x x
ylabel(txt) string txt y y

Basic Operation 49
zlabel(txt) ( 3 ) z
text(x,y,txt) string txt plot coordinate (x,y)
Text vector string
vector x y txti (xi, yi)
text(x,y,txt,sc)
string txt plot coordinate (0,0)
(1,1) plot
legend(txt1,txt2,...)
legend curve plot txt1 curve
plot , txt2 curve plot

Legend(txt1,txt2,...,pos)
legend curve plot txt1 curve
plot , txt2 curve plot
pos pos

0 =
1 = ( MATLAB
)
2 =
3 =
4 =
-1 =
legend off legend plot

legend (M,txt1,txt2,...)
M handle legend M
M = plot(x,y,...) help legend

50 Basic Operation
plot MATLAB x, y
plot
axis

axis([Xmin, Xmax, Ymin, Ymax, Zmin, Zmax])


( z
3 )
axis(axis) Lock scaling plot
plot
hold
axis(string)
string string

auto Reset scaling MATLAB auto mode
ij y
xy y
equal x y scale
square
normal
off MATLAB plot
on MATLAB plot

axis auto, axis on,...


grid

grid on
grid off
grid grid on grid off grid off grid on
q Graphic
graphic window
figure graphic window MATLAB
plot
clf graphic window
clc command window

Basic Operation 51
hold on graphics window plot plot
plot
hold off hold on
hold hold on hold off
ishold MATLAB hold plot hold 1
0

r Subplot
graphic window
MATLAB 1 Graphic window
sub - plot graphic window subplot
subplot(m,n,p)
sub-plot graphic window
matrix m x n plot sub-plot p
p 1 sub-plot

subplot subplot window subplot (1,1,1)

x=0:pi/100:2*pi;
y=sin(x);
z=cos(x);
plot(x,y,'+',x,z,'-')

52 Basic Operation
1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

x=[10 12 14 16 18];
y=[1 2 3 4 5;1.2 2.3 3.4 4.5 5.6];
plot(x,y)
xlabel('This is X-axis title')
ylabel('This is Y-axis title')
title('This is Titel of the graph')
text(14,1.5,'This Text start at point (14,1.5)')
legend('First Graph','Second Graph',0)

Basic Operation 53
This is Titel of the graph
6
First Graph
5.5 Second Graph

4.5
This is Y-axis title

3.5

2.5

1.5 This Text start at point (14,1.5)

1
10 11 12 13 14 15 16 17 18
This is X-axis title

legend MATLAB handel


x=0:pi/50:4*pi;
y=x.*sin(x).*exp(-x);
z=x.*cos(x*10).*exp(x/20);
y=100*x.*sin(x).*exp(-x);
m=plot(x,y,'r-.',x,z,'b--');
xlabel('This is X-axis title')
ylabel('This is Y-axis title')
title('This is Titel of the graph')
legend(m,'First Graph','Second Graph',3)

54 Basic Operation
This is Titel of the graph
40

30

20
This is Y-axis title

10

-10

-20
First Graph
Second Graph
-30
0 2 4 6 8 10 12 14
This is X-axis title

plot subplot
x=[10 12 14 16 18];
y=[1 2 3 4 5; 1.2 2.3 3.4 4.5 5.6];
subplot(2,2,1);
plot(x,y)
title('This is the graph at position 1 of 2x2')
subplot(2,2,2);
semilogx(x,y)
title('This is the graph at position 2 of 2x2')
grid on
subplot(2,2,3);
semilogy(x,y)
title('This is the graph at position 3 of 2x2')
subplot(2,2,4);
loglog(x,y)
title('This is the graph at position 4 of 2x2')
grid on

 Figure Windows

MATLAB 5.3 MATLAB 6.0
graphic windows toolbars

sine MATLAB
X=linspace(0,4*pi);

Basic Operation 55
y=sin(x);
plot(x,y)

figure windows

Edit Current Object Properties Property Editor


Plot


Edit
Axes Properties Property Editor

56 Basic Operation





Graphic



M-file

"
Potential Flow
potential flow half-body (Uniform
flow Source) stream function

q
= Ur sin +
2

Basic Operation 57
U
q flow rate source source strength
plot = stream line plot
r = f()
q

2
r=
u sin

plot x-y polar coordinate


x = r cos y = r sin
zeta=linspace(pi/160,159*pi/160,50);
q=10;U=10;
phi=linspace(q/2,1.5*q,10);

for m=1:10 % FOR-Loop M-FILES m


% stream function stream lines
r(m,:)=(phi(m)-(q*zeta/(2*pi)))./(U.*sin(zeta));
end

r=abs(r');zeta=zeta';

for m=1:10
x(:,m)=r(:,m).*cos(zeta);
y(:,m)=r(:,m).*sin(zeta);
end

hold on
plot(x,y);y=-y;plot(x,y);
title('Flow Over Half Body')
axis([-2 6 -1.5 1.5])
axis off;hold off

58 Basic Operation
Flow Over Half Body

plot Contour plot


3

Single Degree of Freedom


Single Degree of Freedom Force Vibration

mx + cx + kx = F0 cos t

m stiffness k damping c harmonic F0


x x

x = Ae nt sin(d t + ) + A0 cos(t )

parameter
n =
k
m
natural frequency ,
=
c
damping ratio
2 km
d = n 1 2 damping frequency


Transient Vibration Steady State

Basic Operation 59
A0

f0 f0
A0 = =
(n2 ) + (2n )
2 2 2
n2 (1 r 2 ) 2 + (2r ) 2
Phase angle
2r
= tan 1
1 r2


Normalized magnitude AF0 k Phase angle, frequency ratio, r = damping
0 n

ratio
r=linspace(0,3,200);
r=r';
s=0.1;
x=1./sqrt((1-r.^2).^2+(2*s*r).^2);
phi=atan2(2*s*r,1-r.*r);
subplot(2,1,1)
a(1)=plot(r,x);
hold on
subplot(2,1,2)
b(1)=plot(r,phi);
hold on

s=0.25;
x=1./sqrt((1-r.^2).^2+(2*s*r).^2);
phi=atan2(2*s*r,1-r.*r);
subplot(2,1,1)
a(2)=plot(r,x,'b-.');
subplot(2,1,2)
b(2)=plot(r,phi,'b-.');

s=0.707;
x=1./sqrt((1-r.^2).^2+(2*s*r).^2);
phi=atan2(2*s*r,1-r.*r);
subplot(2,1,1)
a(3)=plot(r,x,'b:');
subplot(2,1,1)
b(3)=plot(r,phi,'b:');

s=1.0;
x=1./sqrt((1-r.^2).^2+(2*s*r).^2);
phi=atan2(2*s*r,1-r.*r);
subplot(2,1,1)
a(4)=plot(r,x,'b--');
xlabel('Frequency Ratio');
ylabel('Normalized Magnitude');
legend(a,'0.1','0.25','0.707','1.0')
subplot(2,1,2)
b(4)=plot(r,phi,'b--');
xlabel('Frequency Ratio');
ylabel('Phase Angle, Rad');

60 Basic Operation
legend(b,'0.1','0.25','0.707','1.0')

Normalized Magnitude
0.1
0.25
4 0.707
1.0

0
0 0.5 1 1.5 2 2.5 3
Frequency Ratio
4
0.1
Phase Angle, Rad

3 0.25
0.707
1.0
2

0
0 0.5 1 1.5 2 2.5 3
Frequency Ratio

Basic Operation 61
3 MATLAB FUNCTIONS

MATLAB MATLAB
function function
sub-directories file M-file M-file
function
function function parameter
( )
function(parameter1,parameter2,...)

sin(x) sine x
abs(x) absolute parameter x

x scalar, vector matrix

3.1
MATLAB function

abs(x) absolute x
sqrt(x) 2 x

round(x) x x
fix(x) x x

floor(x) x x x - infinity
ceil(x) x x x + infinity
sign(x) x -1 x < 0, 1 x > 0 0 x = 0
rem(x,y) x y x/y
exp(x) ex
log(x) ln(x) natural logarithm x
log10(x) log10 x logarithm 10 x

62 MATLAB Function
3.2
MATLAB Radians
180 = rad

sin(x) sine x radians


cos(x) cosine x radians
tan(x) tangent x radians
asin(x) arcsine inverse sine x 1 1
radians
2 2
acos(x) arccosine inverse cosine x 1 x 1
radians 0
atan(x) arctangent inverse tangent x x
2 2
atan2(x,y) arctangent inverse tangent y/x function radians
x y

function MATLAB

1 1 1
sec( x ) = , cos ec( x ) = , cot( x ) =
cos( x ) sin( x ) tan( x )
1
arc sec( x) = arc cos x 1
x
1
arc cos( x) = arc sin x 1
x
x
arc cot( x) = arc cos

1+ x
2

3.3 Hyperbolic Functions


Hyperbolic Functions function natural exponential function, ex inverse hyperbolic
function function natural logarithm functions, MATLAB function
hyperbolic function
e x ex
sinh(x) hyperbolic sine x 2
e x + ex
cosh(x) hyperbolic cosine x 2

MATLAB Function 63
tanh(x) hyperbolic tangent x sinh( x )
cosh( x )
asinh(x) inverse hyperbolic sine x ln x + x 2 + 1

acosh(x) inverse hyperbolic cosine x ln x + x 2 1

x 1

1+ x
atanh(x) inverse hyperbolic tangent x ln x 1
1 x

hyperbolic function MATLAB function

coth( x ) =
cosh( x )
sinh( x )
x 0, sech( x ) =
1
cosh( x )

x + 1
csch( x ) =
1
sinh( x )
, acoth( x ) = ln
x 1
x 1

1 1+ x 2 1+ 1 x2
acsch(x ) = ln +
x
,

asech( x ) = ln



0 x 1
x x

3.4 Complex Number Functions


Complex number z
z = x + iy

x y real i = 1
x real part z ; x = Re(z)
y imaginary part z ; y = Im (z)

MATLAB i j 1 i j
imaginary number function complex number MATLAB parameter z = x + iy

conj(z) complex conjugate z z = x + iy, x - iy


real(z) Real part z z = x + iy, x
imag(z) imaginary part z z = x + iy, y
abs(z) absolute z x 2 + y 2
angle(z) argument z angle (z) = tan xy
1

64 MATLAB Function
3.5 Polynomial Functions
polynomial
P ( x ) = a n x n + a n1 x n 1 +....+ a 2 x 2 + a1 x + a 0

coefficient polynomial P(x) n


a n , a n1 ,... a o

polynomial degree n polynomial degree n MATLAB coefficient


vector n+1
P = [a n , a n 1 ,... a 2 , a1 , a 0 ]

vector P polynomial function


polynomial
polyval(P,x) polynomial coefficient P x x scalar function
x x vector vector x
element function element x

P=[1, 2, 1] % f ( x) = x + 2 x + 1 2

Polyval(P,1)% f(1) 1
ans =
1

x=[1 2 3 4];
polyval(P,x)
ans =
4 9 16 25

n Polynomial
polynomial P(x) x P(x) = 0
order () polynomial complex
number MATLAB
polynomial roots
roots(A) polynomial A

x4 = 4 x4- 4 = 0
A=[1,0,0,0,-4];
B=roots(A)
B =
-1.4142
0.0000+ 1.4142i

MATLAB Function 65
0.0000- 1.4142i
1.4142

4 2 , 2i

D=[1,3,0,-1,0,2];
C=roots(D)
C =
-2.9098
-0.7186+ 0.6574i
-0.7186- 0.6574i
0.6735+ 0.5207i
0.6735- 0.5207I

o polynomial
MATLAB roots polynomial
poly
poly(A) polynomial vector A

B=[1,-3,-1,3];
A=roots(B)
A =
3.0000
1.0000
-1.0000
C=poly(A)
C =
1.0000 -3.0000 -1.0000 3.0000
C B

p polynomial
polynomial scalar polynomial scalar

P=[1, 2, 1] % P( x ) = x 2 + 2 x + 1
Q=2*P % Q( x) = 2( x 2 + 2 x + 1) = 2 x 2 + 4 x + 2
polyval(Q,1) % Q(1)
ans =
8

polynomial polynomial
MATLAB conv
conv(P,Q) polynomial
polynomial P Q

66 MATLAB Function

P=[1 2 1]; % P( x ) = x 2 + 2 x + 1
Q=2*P; % ( )
Q( x ) = 2 x 2 + 2 x + 1 = 2 x 2 + 4 x + 2

conv(P,Q) % P(x)*Q(x)
ans =
2 8 12 8 2

polynomial polynomial
MATLAB polynomial
decond
[A,B]=deconv(C,D) MATLAB polynomial C
polynomial D polynomial A
polynomial B

C=[3,4,-9,13,-1,1.5,-10.5,10,10];
D=[1,3,0,-1,0,2.5];
[A,B]=deconv(C,D)
A =
3 -5 6 -2
B =
0 0 0 0 0 0 0 -5 15

polynomial 3x 3
5x 2 + 6 x 2 polynomial 5x + 15
0 parameter function polynomial
vector parameter matrix MATLAB
row 1 row matrix row row parameter

3.6 Statistical and Logical Functions


n Statistical Functions
function MATLAB function
max(x) MATLAB x x matrix row
vector column x x complex
number
[y,ind] = max(x) MATLAB row vector y column
matrix x ind element
column x

MATLAB Function 67
max(A,B) MATLAB matrix A B
element (i, j) aij bij

function min function max

sum(x) x vector element x


x matrix row vector column
x
cumsum(x) x vector x element 2
element 1 2 x , element 3
element 1, 2 3 x x matrix MATLAB
column x
prod(x) sum element
cumprod(x) cumsum element
mean(x) x vector element x x
matrix row vector element column
x
median(x) x vector median element x x
matrix row vector element medien
column x
std(x) x vector (standard
deviation) element x x matrix row
vector element column
x
cov(x) x vector Varian x x matrix
diagonal matrix Varian column x
corrcoef(A) correlation matrix matrix A
sort(x) x vector vector element
x matrix matrix
column
column x

68 MATLAB Function
[y,ind] = sort(x) y sort (x) ind index
element x
column vector x, row vector y, matrix A
x=[4;1;6]
x =
4
1
6
y=[1 8 9]
y =
1 8 9

A=[1 9 8;2 12 4;4 7 6]


A =
1 9 8
2 12 4
4 7 6

max(y)
ans =
9

min(A)
ans =
1 7 4

sort(x)
ans =
1
4
6

mean(A)
ans =
2.3333 9.3333 6.0000

sum(y)
ans =
18

cumsum(x)
ans =
4
5
11

cumprod(A)
ans =
1 9 8
2 108 32
8 756 192

o Logical Function

MATLAB Function 69
MATLAB function function
, element matrix element matrix function

find(x) vector element x x


matrix column vector column
x vector
any(x) 1 element x element x
0 x matrix row vector
column column x
all(x) 1 element x element x
0 x matrix row vector
column column x
isnan(x) 1 element x ( Not-a-
Number, NaN) 0
finite(x) 1 element x finite 0
element x NaN infinity
isempty(x) 1 x matrix 0


B=[1 0 4;3 6 0;4 2 9]
B =
104
360
4 -2 9

any(B)
ans =
1 1 1

find(B)
ans =
1
2
3
5
6
7
9

all(B)
ans =
1 0 0

70 MATLAB Function
finite(B)
ans =
1 1 1
1 1 1
1 1 1

3.7 File Input/Output Functions


MATLAB


--- file MATLAB
- file



file file
disk file
file

n file
MATLAB file fopen
fid=fopen(filename, permission)
file filename file
permission file directory
MATLAB MATLAB search path.
fid file identifiers file
MATLAB file
permission strings
'r' (read)

'w' file

'a' (append)

'r+'

'w+'

'a+'

MATLAB Function 71
file format binary code
file text 't' string
'rt' 'wt+' UNIX Macintosh text file

binary file PC file


file MATLAB
fid = -1 fid =1, 2 3 MATLAB
file string PC
directory DOS

fids=fopen('all') row vector file identifiers file


file fclose
st=fclose(fid) file file identifier, fid, fopen
st =0 file st = -1

st=fclose('all') file

o Binary File
binary file fread fwrite

[A,count]= fread(fid,size,precision)
binary data file fid
matrix A count
size
MATLAB file

N N element column vector
inf file ()
[M,N] matrix M x N column

count=fwrite(fid,a,precision)

72 MATLAB Function
element matrix A file fid
MATLAB column count
elements

precision

String
'char' - 8 bits
'uchar' unsigned character - 8 bits
'schar' signed character - 8 bits
'int8', 'int16','int32','int64' - 8,16,32 64 bits
'uint8', 'uint16', 'uint32', 'uint64' unsigned integer - 8,16,32 64 bits
'float32' floating point - 32 bits
'float64' floating point - 64 bits

computer

'short' - 16 bits.
'int' - 32 bits.
'long' - 32 64 bits.
'ushort' unsigned integer - 16 bits.
'uint' unsigned integer - 32 bits.
'ulong' unsigned integer - 32 bits or 64 bits.
'float' floating point - 32 bits
'double' floating point - 64 bits.

binary file
file

f1=fopen('c:\MATLABR11\work\myio1.dat','w');
A=linspace(0,2*pi,10);
st =fwrite(f1,A,'float32')

MATLAB Function 73
st =
10

file
f2=fopen('c:\MATLABR11\work\myio1.dat','r');
B=fread(f2,'float32');
fclose(f2);

file
f3=fopen('c:\MATLABR11\work\myio1.dat','r');
C=fread(f2,[2 5],'float32');
fclose(f3);

file
F4=fopen('c:\MATLABR11\work\myio1.dat','r');
D=fread(f2,[2,2],'float32');
E=fread(f2,[3,2],'float32');
fclose(f4);

B C D E
B =
0
0.6981
1.3963
2.0944
2.7925
3.4907
4.1888
4.8869
5.5851
6.2832

C =
0 1.3963 2.7925 4.1888 5.5851
0.6981 2.0944 3.4907 4.8869 6.2832

D =
0 1.3963
0.6981 2.0944

E =
2.7925 4.8869
3.4907 5.5851
4.1888 6.2832

74 MATLAB Function
binary file IEEE
MATLAB C FORTRAN
help fread

p Format File
text file file binary file
fscanf fprintf
[a,count]=fscanf(fid,format,size)
format file fid
format matrix a
count size
fread
format string %
d, i, o, u, x, e, f, g, s, c, [. . .] (scanset).
C %s character string,
%f floating point %d decimal point integer
MATLAB

count=fprintf(fid,format,a)
format data real part matrix a
format string file fid count
file

file text file iotest.txt


x=linespace(0,5,10);
y=[x,cos(x)];
f1=fopen('c:\MATLABR11\work\iotest.txt','wt');
fprintf(f1,'%8.4f %8.4f\n',y);
fclose(f1);

f2=fopen('c:\temp\iotest.txt','rt');
A=fscanf(f2,'%f %f',[2 5]);
B=fscanf(f2,'%f');

A
A =
0 1.1111 2.2222 3.3333 4.4444
0.5556 1.6667 2.7778 3.8889 5.0000

MATLAB Function 75
B
B =
1.0000
0.8496
0.4437
-0.0957
-0.6063
-0.9345
-0.9817
-0.7335
-0.2647
0.2837

function MATLAB function


function MATLAB
help files

"
Stress-Strain Curve
curve
stress-strain curve curve

stress strain

 Youngs Modulus MPa
 Ultimate Strength MPa
 Percent Elongation at Fracture

Stress (kpsi) Strain (in/in) Stress (kpsi) Strain (in/in)


0 0 76 0.08
30 0.001 75 0.10
55 0.002 73 0.12
60 0.005 69 0.14
68 0.01 65 0.16
72 0.02 56 0.18
74 0.04 51 0.19 (Fracture)
75 0.06

76 MATLAB Function
file tensile.dat 2 column stress
strain column
kpsi
MPa 1 kpsi = 6.895 MPa
MATLAB
fopen
fid = fopen('c:\MATLABR11\work\tensile.dat','r');
A=fscanf(fid,'%f %f',[2 100]);
fclose(fid);
A=A';


100 file 2
stress strain 2 x 100 transpose
column

Stress = A(:,1)*6.895;
Strain = A(:,2);

Young Modulus linear


elastic strain Ultimate Tensile Strength

Young = (Stress(3)-Stress(2))/(Strain(3)-Strain(2));
fprintf('Youngs Moduls = %7.3f MPa \n',Young)
Youngs Moduls = 172375.000 MPa

U_Strangth = max(Stress);
fprintf('Ultimate Tensile Stress = %7.3f MPa \n',U_Strangth)
Ultimate Teasel Stress = 524.020 MPa

Elongation at fracture strain


Elongation = (max(Strain)-min(Strain))*100;
fprintf('Percent Elongation at Fracture = %5.2f \n',Elongation)
Percent Elongation at fracture = 19.00

plot(Strain,Stress,'^-');
xlabel('Strain')
ylabel('Stress')
title('Stress - Strain Curve')

MATLAB Function 77

S tres s - S train Curve


600

500

400
S tres s

300

200

100

0
0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.2
S train

78 MATLAB Function
4 M-FILE

4.1 M-File
MATLAB
C, FORTRAN, PASCAL,... MATLAB function

function
MATLAB Save extension " m "
MATLAB M-file M-file 2
script file
function function MATLAB
function M-file function file
M-file MATLAB plain text format program
Notepad save file save file extension m
MATLAB 5.x MATLAB Editor/Debugger
M-file file extension M-file
myfile.m command window MATLAB
myfile

 M-file
MATLAB M-file directory path
MATLAB MATLAB directory sub-directory drive
MATLAB search path M-file
file path MATLAB
M-file directory M-file MATLAB
MATLAB search path directory MATLAB program
search path

M-Files 79
search path MATLAB
addpath directory search path directory

DOS
search path MATLAB 5.X click
File Set path... path

4.2 Script Files & Function Files


MATLAB
function MATLAB

program computer script files

MATLAB (script) function file


script file function file
Function file input file
output script file function file
parameter
script file M-file MATLAB
function file
output
function MATLAB
script file global variable function file local variable

function file
script file
variable M-file
MATLAB input output
function file script file
parameter

0 script file function file M-file


search path MATLAB

80 M-Files
script file function file

function mypro(c)

function MATLAB file function file


c input parameter
mypro function file save mypro. m
function a = myfunc(c,d)

function MATLAB file function file


a output scalar matrix
c, d input parameter
myfunc function file save myfunc. m
function[a, b, c] = tiger(d, e, f, g)
function file tiger (Save tiger.m) input d, e, f
g a, b c output

0 Function file function M-file Save


function

 Comment ( % )
comment
%
comment MATLAB
% help M-file
script file %
help file
function file % function
help
file

M-file

M-Files 81
script file
% Pythagoras Theorem for Me
a = input (Please input the first side);
b = input (Please input the second side);
c = sqrt (a^2 + b^2)

save file pyta.m


pyta
Please input the first side 3
Please input the second side 4
c =
5

help pyta
Pythagoras' Theorem for Me

function file
function c = pyta (a, b)
% Pythagoras Theorem for Me
% format is c=pyta(a,b)
% where a and b are sides of the rectangle
% and c^2 =a^2+b^2
c = sqrt(a^2 + b^2)
Save file pyta.m
c = pyta(3, 4)
c =
5
Pyta (3,4)
ans =
5
x= Pyta (4, 3)
x =
5

help pyta


Pythagoras Theorem for Me
format is c=pyta(a,b)
where a and b are sides of the rectangle
and c^2 =a^2+b^2

M-file

82 M-Files
4.3 M-File
program computer MATLAB
program C, FORTRAN BASIC

MATLAB line number
subroutine function
MATLAB string, integer
precision
array dimension
function MATLAB
subroutine
MATLAB compile MATLAB
error


For loop Repetitive Control Structure
If - elseif - else - end Conditional Control Structure
While loop Repetitive Control Structure

n For Loop
For loop For loop ( Do loop)
for m = a: b

end

MATLAB (loop) m = a
end MATLAB
for m = a + 1
m = b a b

for m = a:b:c l a c b

M-Files 83
0 FORTRAN loop i j
integer FORTRAN MATLAB
MATLAB imaginary number 1
For Loop
for loop

for k = 1 : 5
for i = 1 : 5
p(k,i) = k * i ;
end
end

matrix p 5x5 element


row column k = 1 loop i = 1
P(1,1) = 1*1=1 end loop 2
k 1 i = 2 P(1,2) = 1*2=2 i = 5
for loop end loop
end loop k = 2
loop i = 1, 2, 3, 4, 5 loop
k = 5 l = 5
MATLAB 5.x M-file Editer MATLAB loop
loop MATLAB
loop end for loop
loop

o If Statement
If

if

end

MATLAB MATLAB
end condition

84 M-Files
MATLAB
= ==
~=
MATLAB
> >
< <
=>
=<
AND &
OR |

if x == 0
a =5
end

x = 0 a = 5 x a = 5

If-Elseif-Else
else elseif
if 1
1
elseif 2
2
elseif 3
4
................
else n
n
End

1 MATLAB 1 end
MATLAB 2 MATLAB 2 end
MATLAB 3 MATLAB 3 end

M-Files 85
n MATLAB
end

p While - Loop
while loop for loop while loop
for loop loop
while-loop
while

end

loop MATLAB
end

a =0
while a < 5
a =a +1
b =5+a
end

a = 0 loop while a < 5 MATLAB a = 0


+ 1 = 1 b = 5 + 1 = 6 end MATLAB while a = 1
a < 5 MATLAB
a 5

0 loop
loop loop

Ctrl-C MATLAB

q Loop
program loop
Break

86 M-Files
MATLAB loop
end
for k = 1 : 5
y = k^2
if y = = 9
break
end
x = 5/(y-9)
end
MATLAB loop y y 9
MATLAB x y = 9 MATLAB
If (break) MATLAB
end loop for loop
control flow MATLAB 5.X switch - case

switch
case 1
1
case 2
2
case 3
3
...............
otherwise
n
end

switch MATLAB

x=input(' 1-4 \n');


switch x
case 1
fprintf(' 1 \n')
case 2
fprintf(' 2 \n')
case 3
fprintf(' 3 \n')
case 4

M-Files 87
fprintf(' 4 \n')
otherwise
fprintf(' \n')
end

x x MATLAB x
x = 1 1

r
MATLAB
pause keyboard

pause(n) n
return M-file M-file

pause on off pause M-file

M-file
function MATLAB

88 M-Files
5 SOLUTION TO SYSTEM OF LINEAR EQUATIONS

5.1
n 1
nonlinear function function sin, log
n

a11 x1 + a12 x 2 + ... + a1n xn = b1


a 21 x1 + a 22 x 2 + ... + a 2 n x n = b2

............
a n1 x1 + a n 2 x2 + ... + a nn xn = bn

matrix

[ A]{ x} = {b}

[A] [n x n] matrix { x} {b} [n x 1] vector

{b} { 0} ; { x} [A] inverse ( det( A) 0 )


{b} = {0} { x} non-trivial solution ({ x} 0) det( A) = 0
eigenvalue problems
{b} { 0} ; [A] inverse ( det( A) = 0 ) { x} unique

{b} {0} [A] inverse

[ A] 1[ A]{x} = [ A] 1 {b}
{ x} = [ A]1 {b}

System of Linear Equations 89


MATLAB variable x n-linear equations [A] {b}
x MATLAB
MATLAB 2
Inverse
Matrix

Numerical method
MATLAB

5.2 Inverse
inverse
MATLAB
inverse Matrix MATLAB x

[ A]{ x} = {b}

x=inv(A)*b

x
2 x1 + x 2 = 1
x1 + 3x 2 + 5x 3 = 2
4 x1 6x 2 + 8x 3 = 4

MATLAB
A=[2,1,0;1,3,5;4,-6,8];
B=[1;2;4];
X=inv(A)*B
X =
0.4833
0.0333
0.2833

D=B-A*X
D =
1.0e-015 *
0.4441
0

90 System of Linear Equations


0

x1 0.4441 x 10-15
inverse Matrix
analytical numerical
inverse Matrix MATLAB
matrix X = B/A X = A\B

5.3 Matrix
matrix MATLAB
MATLAB
Gaussian Elimination inverse matrix
inverse
matrix ill-condition matrix
singular matrix ( matrix determinant ) inverse
floating point Gaussian Elimination
Method ill-condition

[ A]{ x} = {b}

MATLAB matrix
x=A\b

A=[2,1,0;1,3,5;4,-6,8];
B=[1;2;4];
X=A\B
X =
0.4833
0.0333
0.2833

D=B-A*X
D =
0

System of Linear Equations 91


0
0

5.4 Eigenvalues Eigenvectors



Ax = x

A square matrix
x column vector
scalar

solution x { x} = { 0} element x solution trivial


solution scalar non-trivial solution
eigenvalues matrix A x eigenvalue eigenvector
eigenvalue problem

( A I ) x = { 0}

{ x} {0} matrix ( A I ) inverse matrix C d

[ C]{ d } = { 0}

C inverse [ C] [ C]{d } = [ C] {0}


1 1

{ d } = { 0}

{d } {0} C inverse

92 System of Linear Equations


( A I ) inverse
matrix ( A I ) determinant matrix 0

A I = 0

characteristic equation matrix A unique


x 1 ( A I ) x = { 0} eigenvector x
orthogonal matrix Q orthogonal matrix

QQ T = I Q T = Q 1

eigenvector orthogonal normalized eigenvector


eigenvalue dot product eigenvector orthonormal
vector MATLAB eigenvalue problem function

eig(A) column vector eigenvalue matrix A


[Q, b]= eig(A)
square matrix Q column eigenvector A square
matrix b eigenvalue A diagonal 0

A=[1 4;8 9];


eig(A)
ans =
-1.9282
11.9282

[B,C]=eig(A)
B =
-0.8069 -0.3437
0.5907 -0.9391
C =
-1.9282 0
0 11.9282

System of Linear Equations 93


"
eigenvalue
Principal Stress Natural Frequency N-DOF

Principal Stress
Principal Stress Principal Direction stress
system
xx = 120, yy = 55, zz = 85, xy = 55, yz = 33, zx = 75 MPa

stress tensor 3x3


s=[120 -55 -75;-55 55 33;-75 33 -85]
s =
120 -55 -75
-55 55 33
-75 33 -85

eigenvalue eigenvector
[Direc SP]=eig(s)
Direc =
-0.4654 -0.8372 0.2872
-0.8836 0.4587 -0.0944
0.0527 0.2977 0.9532

SP =
24.0644 0 0
0 176.7995 0
0 0 -110.8640

eigenvalue matrix vector


S=diag(SP)
S =
24.0644
176.7995
-110.8640

Maximum Shearing Stress


MaxShear=(max(S)-min(S))/2
MaxShear =
143.8318

94 System of Linear Equations


Natural Frequency
Vibrations Egienvalue Problem Natural Frequency
Mode Shapes damp

Mx + Kx = 0

d 2x
x column vector coordinate x = M mass matrix K
dt 2
stiffness matrix harmonic

x = Ae it

A x = 2 Ae it

[ K M ]x = 0
2

[ AM ]x = 0

A = K-1 influence coefficient matrix =


1
eigenvalue
2
problem x unique solution
mode shape
natural frequency mode shape
3-DOF Mass Stiffness Matrix

m1 0 0 k1 + k 2 k2 0
M = 0 m2 0 K = k 2 k2 + k3 k 3
0 0 m3 0 k3 0

MATLAB Natural Frequency Mode Shape function file


threeDOF.m M = [m1 m2 m3] K = [k1 k2 k3 ] vector
( matrix M K )
function [A,B]=threedof(M,K)
m=zeros(3,3);
k=zeros(3,3);
for j=1:3;
m(j,j)=M(j);
end
k(1,1)=K(1)+K(2);
k(2,2)=K(2)+K(3);

System of Linear Equations 95


k(3,3)=K(3);k(1,2)=-K(2);k(2,3)=-K(3);
k(2,1)=-K(2);k(3,2)=-K(3);

% A - Influence Coefficient Matrix A=inv(K)


invk =inv(k);

% D - Dynamics Matrix D = inv(K)*M


D = invk*m;
% Natural Frequency Mode Shapes
[A B]=eig(D);
B=diag(B);
1
B=sqrt(abs(1./B)); % =
2
% Plot Mode Shapes
X=[0 1 2 3]';
subplot(3,1,1);
Y=[0;A(:,1)];
plot(X,Y);
subplot(3,1,2);
Y=[0;A(:,2)];
plot(X,Y);
subplot(3,1,3);
Y=[0;A(:,3)];
plot(X,Y);

m1= m2= m3=1 kg k1 = k2 = k3 = 10 N/mm function threeDOF

M=[1 1 1];
K=[10 10 10];
[A B]=threedof(M,K)
A =
0.5910 -0.7370 0.3280
-0.7370 -0.3280 0.5910
0.3280 0.5910 0.7370
B =
5.6982
3.9433
1.4073

fundamental frequency () 1.4073 rad/sec Mode Shape

96 System of Linear Equations


1

-1
0 0.5 1 1.5 2 2.5 3
1

-1
0 0.5 1 1.5 2 2.5 3
1

0.5

0
0 0.5 1 1.5 2 2.5 3

eigenvalue

System of Linear Equations 97


6 INTERPOLATION CURVE FITTING

6.1 Interpolation Curve Fitting





function function
2
1. Interpolation
2. Curve Fitting

2 interpolation function curve


fitting function
function curve
2 MATLAB

1. Interpolation MATLAB
Polynomial interpolation - 2
linear interpolation
Cubic-Spline interpolation - curve polynomial degree 3 2
slope
curve curve

n curve n-1 linear
interpolation curve cubic spline curve polynomial
degree 3
2. Curve fitting MATLAB Least-Square Curve Fitting curve
polynomial degree curve

98 Interpolation and Curve Fitting


curve curve fitting MATLAB
polynomial

Numerical Analysis
MATLAB

6.2 Interpolation
n Linear Interpolation
linear interpolation


MATLAB interp1

Interp1(x,y,s) linear interpolation x y y = y(x)


y(s) x y vector
s vector vector s

0 interp1 x MATLAB x


() ()
0 0
1 200
2 600
3 680
4 800

Interpolation and Curve Fitting 99


t = 2.5 linear interpolation

x = [0 1 2 3 4]; % x
y = [0, 200, 600, 680, 800];
y1 = interp1(x, y, 2.5)
y1 =
640

t = 1.5 35 linear
interpolation ( x y )
s = [1.5 3.5];
y2 = interp1(x, y, s);
y2 =
400 740

t = 15 400 t = 3.5 740

0 x y matrix MATLAB column


column

o Cubic Interpolation
function cubic interpolation spline curve

interp1(x,y,s,cubic) x, y, s string cubic
MATLAB cubic interpolation

x = [0, 1, 2, 3, 4];
y = [0, 200, 600, 680, 800];
y1 = interp1(x, y, 2.5,'cubic')
y1 =
657.5000

1.5 3.5
s = [1.5 3.5];
y2 = interp1(x, y, s,'cubic')
y2 =
407.5000 735.0000

100 Interpolation and Curve Fitting


linear spline
function

p Spline Interpolation
spline interpolation function
interp1(x,y,s,spline) x, y, s string spline
MATLAB cubic spline
interpolation
2.5 cubic spline
x = [0, 1, 2, 3, 4];
y = [0, 200, 600, 680, 800];
y1 = interp1(x, y, 2.5,'cubic')
y1 =
657.5000

1.5 3.5 cubic spline interpolation

s=[1.5 3.5];
y1 = interp1(x, y, s,'spline')
y1 =
421.2500 698.7500

spline

spline(x,y,s) interp1 (x, y, s, spline) spline


x, y vector
spline(x,y) piecewise polynomial interpolate (x, y)
polynomial y = y(x) polynomial pp-
form polynomial function
ppvalue
ppval(pp,s) pp pp-form polynomial, s
spline(x, y, s)


spline(x,y,s)
ans =
421.2500 698.7500

Interpolation and Curve Fitting 101



p=spline(x,y);
u=ppval(p,s)
u =
421.2500 698.7500

q Interpolation


y = x sin( x)

x y vector 1x 20 x
0 2 interpolation x
= 5 M-file
% Interpolation Demo
x=0:pi/5:2*pi;
y=x.*sin(x);
s=0:pi/30:2*pi; % Set interval for plot

% Linear
a=interp1(x,y,s);
a1=interp1(x,y,5);

% Cubic
b=interp1(x,y,s,'cubic');
b1=interp1(x,y,5,'cubic');

% Cubic Spline
c=interp1(x,y,s,'spline');
c1=interp1(x,y,5,'spline');

% Exact
d1=5*sin(5);
fprintf('Solution of x*sin(x) at x=5 by linear inter.= %f \n',a1)
fprintf('Solution of x*sin(x) at x=5 by cubic inter. = %f \n',b1)
fprintf('Solution of x*sin(x) at x=5 by spline inter. = %f \n',c1)
fprintf('Exact solution of function x*sin(x) at x=5 = %f \n',c1)

subplot(3,1,1)
plot(s,a,'-',x,y,'o')
text(5,2,'Linear Interpolation')
subplot(3,1,2)
plot(s,b,'-',x,y,'o')
text(5,2,'Cubic Interpolation')

subplot(3,1,3)
plot(s,c,'-',x,y,'o')
text(4,2,'Cubic Spline Interpolation')

102 Interpolation and Curve Fitting


Solution of x*sin(x) at x=5 by linear inter. = -4.755283
Solution of x*sin(x) at x=5 by cubic inter. = -4.796262
Solution of x*sin(x) at x=5 by spline inter. = -4.795152
Exact solution of function x*sin(x) at x=5 = -4.795152

Linear Interpolation
0

-5
0 1 2 3 4 5 6 7
5

Cubic Interpolation
0

-5
0 1 2 3 4 5 6 7
5

Cubic Spline Interpolation


0

-5
0 1 2 3 4 5 6 7


function

interpolation function MATLAB function


MATLAB help function

interp2 2- interpolation
interp# interpolation # - MATLAB 6-
interpft Fast Fourier Transform Interpolation Method
griddata 2- interpolation

Interpolation and Curve Fitting 103


6.3 Polynomial Curve Fitting
Polynomial curve fitting polynomial degree n

polynomial

P ( x ) = a n x n + a n1 x n 1 +....+ a 2 x 2 + a1 x + a 0

ai
Least square curve fitting polynomial degree
ai

MATLAB

Polyfit(x,y,n) x, y fit curve polynomial degree n


MATLAB polynomial y = f(x)

interpolation fit curve polynomial 2


x = [0, 1, 2, 3, 4];
y = [0, 200, 600, 680, 800];
p=polyfit(x,y,2)
p =
-34.2857 345.1429 -28.5714

curve y = a2x2 + a1x + a0 curve 2


a2 = -34.2857, a1= 345.1429 a0 = - 28.5714 2.5
polyval
y1=polyval(p,2.5)
y1 =
620.0000

1.5 3.5
s=[1.5 3.5];
y1=polyval(p,s)
y1 =
412.0000 759.4286

104 Interpolation and Curve Fitting


interpolation
polynomial degree M-file
% Curve Fitting Demo
x=0:pi/5:2*pi;
y=x.*sin(x);
s=0:pi/30:2*pi; % Set interval for plot
% Linear
a1=polyfit(x,y,1);
a=polyval(a1,s);
% Second order
b1=polyfit(x,y,2);
b=polyval(b1,s);
% Third order
c1=polyfit(x,y,3);
c=polyval(c1,s);
% Fourth order
d1=polyfit(x,y,4);
d=polyval(d1,s);
subplot(4,1,1)
plot(s,a,'-',x,y,'o')
text(4,2,'Linear Least Square')
subplot(4,1,2)
plot(s,b,'-',x,y,'o')
text(4,2,'Second order')
subplot(4,1,3)
plot(s,c,'-',x,y,'o')
text(4,2,'Third order')
subplot(4,1,4)
plot(s,c,'-',x,y,'o')
text(4,2,'Fourth order')

5
Linear Least Square
0

-5
0 1 2 3 4 5 6 7
5
Second order
0

-5
0 1 2 3 4 5 6 7
5
Third order
0

-5
0 1 2 3 4 5 6 7
5
Fourth order
0

-5
0 1 2 3 4 5 6 7

Interpolation and Curve Fitting 105


curve fitting interpolation



interpolation



Least Square Fitting

"

Interpolation Curve Fitting

Impact of a Jet

 (1 cos )
F = mU

m U

2 (flat plat) 90
(hemispherical cup) 180

F = mU


F = 2mU

106 Interpolation and Curve Fitting


F mU 

1 2
600 g

F L = mgl

m g L
150 mm l

mgl
F=
L

TF, VF, TH, LH


T V F H


LF, LH L F H

M-file file M-book


MATLAB Microsoft Word for Windows
M-book LF, TF, VF, LH, TH, VH
Microsoft Word M-file
% Impact of a Jet for M-book

% Initialized Data
LF=LF'; TF=TF'; VF=VF';LH=LH';TH=TH';VH=VH';
% List of Constant
grav = 9.81; % [m/s2]
NozzelDim = 10; % [mm]
High = 35 ; % [mm]
ArmLength = 150; % [mm]
mass = 0.6; % [kg]
% Initialize Figure and hold it
figure('NumberTitle','off','color',[1 1 1])
hold on
% Calculation and Plot for Hemispherical Cub
FlowRate = VH./TH ; % [Liter/s]

Interpolation and Curve Fitting 107


NozzelVel = 4*FlowRate*(10^3)/(pi*NozzelDim^2); %[m/s]
HitVel =sqrt(NozzelVel.^2-(2*grav*High/1000)); % [m/s]
ActualForce = LH * mass * grav /ArmLength; % [Newton]
TheoryForce = HitVel.*FlowRate; % [Newton]
HH=plot(TheoryForce, ActualForce,'b+'); %
p = polyfit(TheoryForce,ActualForce,1); % Polyfit
SlopHemi = p(1,1); % p
MaxOfx = max(TheoryForce);
MinOfx = min(TheoryForce);
xx = linspace(0,MaxOfx);
yy = polyval(p,xx);
plot(xx,yy,'b'); % p
% Calculation and Plot for Flat Plate
FlowRate = VF./TF ; % [Liter/s]
NozzelVel = 4*FlowRate*(10^3)/(pi*NozzelDim^2); % [m/s]
HitVel =sqrt(NozzelVel.^2-(2*grav*High/1000)); % [m/s]
ActualForce = LF * mass * grav /ArmLength; % [Newton]
TheoryForce = HitVel.*FlowRate; % [Newton]
HF = plot(TheoryForce, ActualForce,'ro'); %
p = polyfit(TheoryForce,ActualForce,1); % Polyfit
SlopeFlate = p(1,1);
MaxOfx = max(TheoryForce);
MinOfx = min(TheoryForce);
xx = linspace(0,MaxOfx);
yy = polyval(p,xx);
plot(xx,yy,'r'); % p
H = [HF,HH]; % Legend
legend(H,'Flat Plate','Hemisphrical Cup',0)
xlabel('Rate of Momentum Flow (N)')
ylabel('Force on Vane (N)')
fprintf(' Hemisphrical Cup %5.2f \n',SlopHemi)
fprintf(' Flat Plate %5.2f \n',SlopeFlate)
hold off
% ************* END **************

LF, TF, VF, LH, TH, VH

Hemispherical Cup 1.41


Flat Plate 0.77

108 Interpolation and Curve Fitting


6

Flat Plate
Hemisphrical Cup
5

4
Force on V ane (N)

-1
0 0.5 1 1.5 2 2.5 3 3.5
Rate of Momentum Flow (N)

Interpolation and Curve Fitting 109


7 NUMERICAL INTEGRATION AND DIFFERENTIATION

7.1 Numerical Integration


(Numerical Integration)

1) integrate
interpolation fitting integrate
2) function integrate analytical

integrate
numerical integration
integrate
integrate MATLAB 2
numerical integration function

MATLAB function
numerical integration Trapezoidal Numerical Integration
function integrate numerical
Simpson's Rule function file

n Trapezoidal Numerical Integration


trapezoidal numerical integration MATLAB function trapz
vector matrix x y
trapz(x,y) integrate y( x)dx x y column vector x
y matrix column matrix x column
vector y matrix column y x
integrate

x sin( x)dx
0

110 Integration and Differentiation


integrate-by-path function trapz
x ( x
) 50
x=0:pi/50:pi;

y 50 x
y=x.*sin(x);

A=trapz(x,y)
A =
3.1406

= 3.14159 3

o Quadrature Integration
Quadrature numerical function MATLAB
function 2 function function function
function quad quadz function function file
function file function y = f(x) integrate quad quadz
integrate
quad(function,a,b)

quad(function,a,b,tol,trace)
quad(function,a,b,tol,trace,p1,p2...)
function function file (
function.m) a b integrate a b
tol, trace, p1. tol
relative error integrate MATLAB
0.001, trace function plot p1, p2 parameters
MATLAB help quad
MATLAB Simpson's Rule integrate
Quad8(function,a,b)
Quad8(function,a,b,tol,trace)
Quad8(function,a,b,tol,trace,p1,p2...)
Parameter function
quad

Newton-Cotes 8 panel rule quad

Integration and Differentiation 111


integral function singularity
integrate


function quad M-file function file
save myint.m
function y = myint(x)
y = x.*sin(x);

A=quad('myint',0,pi)
A =
3.1416
= 3.14159 4
function quad8 function myint
format long
A=quad8('myint',0,pi)
A =
3.14159265358962

format long

pi
ans =
3.14159265358979

13
numerical
integration function trapz, quad quad8

trapz integrate
quad quad8 tol quad
quad8 0.001

7.2 Integrate Double Integral


integrate
integrate 2 function
integrate integrate
double integral

112 Integration and Differentiation


1 1
e
x2 y2
dydx
0 0

MATLAB function file myint2.m


function f = myint2(x,y)
f = exp(-x.^2 - y.^2)

integral x x 20
( script file)
x = 0:1/19:1;
for k = 1:20
A2(i) = quad(myint2,0,1,[],[],x(i));
end

integrate quad function integrate 0 1 tol


trace ( [ ]) x(i) M-file myint2
x loop 20 (k = 1 20) A2 matrix 1 x 20
A2 integrate function A2 fixed y x
trapz
A = trapz(x,A2)
A =
0.55762

function integrate double integral function dblquad

dblquad(function,inmin,inmax,outmin,outmax,tol,trace,method)
integrate double integral function quad inmin, inmax
limit integrand outmin outmax limit
integrate function function file integrand
function option tol trace
function quad quad8 method option
integrate quad quad8 MATLAB
quad function file function(inner, outer) inner

outer integrate
function

Integration and Differentiation 113


1 1
e
x2 y2
dydx
0 0

function file integrand myint3.m


function f = myint3(x,y)
f = exp(-x.^2- y.^2);

dblquad('myint3',0,1,0,1)
ans =
0.5577


MATLAB integration
function MATLAB function function function
function function integrate
MATLAB Symbolic Integration Symbolic Toolbox

7.3 Numerical Differentiation


differentiation y(x) x

dy y ( x + x ) y ( x )
= y ( x ) = lim
dx x 0 x

Numerical Differentiation Continuous function


differentiation function analytical integration
function (x,y)
y ( x)

y ( x k ) y ( x k 1 )
y ( x k ) =
x k x k 1

x = x k x k 1 function difference

diff(x) difference element x x vector 1 x n ( n x 1)


vector 1 x (n-1) [ (n-1) x 1] x matrix m x n
matrix (m-1) x n

114 Integration and Differentiation


dy
dx
set coordinate (xi, yi)
diff(y)./diff(x)

x = [1 2 3 4 5] y = [1 1.3 1.8 2.1 2.4] dy


dx

x = [1, 2, 3, 4, 5];
y = [1, 1.3, 1.8, 2.1, 2.4];
dydx = diff(y)./diff(x)
dydx =
0.3000 0.5000 0.3000 0.3000

dy
dx
x=1 0.3000, dy
dx
x=2 0.5000, ...

Numerical differential x = xi-xi-1


x
x
x interpolate
curve fitting difference

"





indicated
power indicator

Indicated mean effective pressure, imep
W
imep =
V
Indicated Power
imepV N
Pi =
nr

Integration and Differentiation 115


V , N nr 1
2 2 4

- -
( CC ) ( bar ) ( bar )
141.0 16.0 15.0
164.25 47.0 11.0
186.50 42.0 9.5
207.55 37.0 8.0
230.00 33.0 7.0
324.13 21.0 4.5
410.40 14.5 3.0
500.00 11.0 2.0
590.04 8.5 1.5
680.00 7.0 1.0
770.00 5.0 1.5
815.00 4.5 1.5
860.00 3.5 3.5

plot Indicator diagram - 4



numerical integration
function file

function [Power,imep]=ice_PV(V,PH,PL,N,nr)
plot(V,PH,V,PL)
ylabel('Pressure, bar');
xlabel('Volume, CC');
title('Indicator Diagram')

DP=PH-PL;

116 Integration and Differentiation


W=(trapz(V,DP))/10; % N-m
Vdis=max(V)-min(V); % Displace Volume
imep = (W/Vdis); % MPa
Power = W*N*2*pi/(nr*60000); % kW

fprintf('Indicated Power = %5.2f kW \n' ,Power)


fprintf('Indicated mep = %5.2f MPa \n' ,imep)

1200 rpm nr = 2 0

N=1200;
nr=2;
[Power imep]=ice_pv(V,PH,PL,N,nr);

Indicated Power = 53.52 kW


Indicated mep = 1.18 MPa

In d i c a t o r D i a g r a m
50

45

40

35

30
P ress ure, bar

25

20

15

10

0
100 200 300 400 500 600 700 800 900
V o lu m e , C C

Integration and Differentiation 117


8 SOLUTION OF ORDINARY DIFFERENTIIAL EQUATIONS





Ordinary Differential Equation (ODE) MATLAB
Partial Differential Equation (PDE) MATLAB toolbox

ODE first order order
MATLAB function initial value problem
function boundary value problems

8.1 First Order ODE


first order ODE

dy
y = = g ( x, y )
dx

x independent variable y dependent variable function x g(x,y)


linear function y ODE linear ODE nonlinear ODE
g(x,y) y
homogenous ODE nonhomogeneous ODE
ODE

y = y ( x) y = g ( x, y )

y(x) 1 function
(initial condition) (boundary condition)
function general solutions y(x) boundary initial

118 Ordinary Differential Equations


condition y(x) particular
solution
ODE MATLAB Runge-Kutta Method (R-K) initial
value problem ordinary differential equations MATLAB variable step size
step size solution step
ODE function MATLAB function-function
function file ODE function file ODE function
function - function integrate
order Runge-Kutta Method MATLAB 2 order 2-3
function ode23 order 4-5 function ode45 ODE functions
[x,y]= ode23('function',[a b],initial)
MATLAB Runge-Kutta Method 2nd- order 3rd - order
function function file [function.m ]
function a b
initial function a (initial
condition) x y y = y(x)
[x,y] = ode45(function,[a b],intial)
parameter ode23 R-K order 4 5
ode23 ode23
relative error 0.001 ode45 relative error 10-6

function ode first order ODE


y ' = cos x x sin x

0 initial condition x = 0, y(0) = 0 exact solution


y = x cos x

function M-file myode.m


function yprime = myode(x, y)
yprime = cos(x) - x.*sin(x)

2 script M-file ( M-file )


[x, y] = ode23(myode,[0 pi],0)

Ordinary Differential Equations 119


column vector x y MATLAB variable step side
x y 0 -
interpolate x y x =
y = p cos(p) = - p =-3.14159

ode23
[a b]=size(y);
y(a)
ans =
-3.1417

y() = -3.1417 ode45

[x, y] = ode45(myode,[0 pi],0)


[a b]=size(y);
format long
y(a)
ans =
-3.14159260200719
pi
ans =
3.14159265358979

y() = - 3.1415926 ode23


ODE function singularity
singularity converge
stiff condition
MATLAB function ODE ode15s, ode23s
help ode23s

8.2 Higher Order ODE


n order ODE
dny
y ( n ) = g ( x, y, y , y ,... y ( n 1) ) y=y(x) y ( n ) =
dx n

initial condition
y( x0 ) = a 0
y ( x 0 ) = a1

..........
y ( n 1) ( x 0 ) = a n 1

120 Ordinary Differential Equations


x independent variable y dependent variable function x
g(x,y,...) linear function y derivative y ODE linear ODE of order n
nonlinear ODE of order n g(x,y,...) y
derivative y homogenous ODE of order n
nonhomogeneous ODE of order n
ODE order 1 ODE
first order ODE

y ( n ) = g ( x, y, y ,... y ( n 1) )

v1 ( x) = y ( n 1)

v 2 ( x) = y ( n 2)

..........
v n 2 ( x) = y
v n 1 ( x) = y
vn = y

v1 ( x) = y ( n ) = g ( x, y, y ,... y ( n 1) )
v 2 ( x) = y ( n 1) = v1 ( x)
v 3 ( x) = y ( n 2) = v 2 ( x)

........
v n 2 ( x) = y = v n 3 ( x)
v n 1 ( x) = y = v n 2 ( x)
v n ( x)= y = v n 1 ( x)

First order n n
nonlinear second order ODE
y = g ( x, y, y ) = y (1 y 2 ) y 2

v1 ( x) = y v1 ( x) = y = y (1 y 2 ) y 2

v2 ( x) = y v2 ( x) = y = v1

v 2 = y,v1 = y v1
v1 = v1 (1 v 22 ) v 22
v 2 = v1

Ordinary Differential Equations 121


v1 v2 function file myode.m
function dv = myode2(x,v)
dv = zeros (2, 1) % vector 2x1
dv (1) = v(1).*(1-(v(2).^2))-v(2).^2;
dv (2) = v(1) ;

initial condition y (0) = 0 = v1 (0)

y (0) = 0.25 = v 2 (0)

0 x 10 MATLAB command
t = [0 10];
initial = [0 0.25];
[x, y] = ode45(myode2,t,initial);
m = plot(x,y);
legend(m,'dy','y')

ode45 vector x 0 10 R-K


variable step size vector y matrix 2 column
column v1 y column 2 v2 y

122 Ordinary Differential Equations


1
dy
0 y

-1

-2

-3

-4

-5

-6

-7

-8

-9
0 1 2 3 4 5 6 7 8 9 10

second order order



order first order
function file first order
ode45 ode23

ode function output


ode23('myode',t,initial)

output function ode23 1 x y MATLAB


ans MATLAB plot (x, y)
option function ode
option function ode help ode23

8.3 Boundary Value Problems : Shooting Method


ODE order 1 condition
order condition
initial value

Ordinary Differential Equations 123


problem boundary
condition analytical method
boundary initial value problems Runge-Kutta numerical method
R-K
R-K solution step
boundary value problem

x
y = x + 1 y y(1) = 2, y(3) = - 1
5

y x = 1 x = 3
R-K ODE
derivative
condition
R-K

shooting method

1 1
1 3-5

MATLAB
ODE order 2 ODE order 1
function dv = myode3(x,v)
dv=zeros(2,1);
dv(1)= x+v(2).*(1-x/5);
dv(2)= v(1);

initial condition y (1) = 1 ( 100%)


init = [-1 2];

1 3

124 Ordinary Differential Equations


intv = [1 3];

ode45
[x,y]=ode45('myode3',intv,init);
[a b]=size(y);
y(a,:)
ans =
6.2568 6.2382

y(3)=6.2382 -1
slope -1 x = 1 y (1) = 1
slop y (1) = 4
init
init=[-4 2];
[x y]=ode45('myode3',intv,init);
[a b]=size(y);
y(a,:)
ans =
-0.6125 -2.4651

y(3) = - 2.4651 -1
y' -1 -4 interpolate
-1 linear
interpolation
4 ( 1)
1+ ( 1 6.2382) = 3.495
2.4651 6.2382

y (1) = 3.495
init=[-3.495 2];
[x y]=ode45('myode3',intv,init);
[a b]=size(y);
y(a,:)
ans =
0.5439 -1.0000

y(3) = 1
m=plot(x,y);
legend(m,'dy','y')

Ordinary Differential Equations 125


2
dy
y
1

-1

-2

-3

-4
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3


linear interpolation 3 3

Boundary Value Problems

ODE second order linear ODE
shooting method boundary value problem ODE linear
linear interpolation

n Shooting Method Linear ODE


Boundary Value Problem linear ODE
2 3 linear interpolation

G1 1
G2 2
R1 1 ( G1)
R2 2 ( G2)
D
3 G

126 Ordinary Differential Equations


G 2 G1
G = G1 + ( D R1)
R2 R1

third order ODE boundary value problems


( order ODE)
2

fourth order ODE 2


interpolate
ODE order

o Nonlinear ODE
nonlinear ODE 3

x
y = x + 1

yy
5
y(1)=2 y(3) = -1

nonlinear yy
MATLAB
script file
function file myode4.m

function dv = myode4(x,v)
dv = zeros(2,1);
dv(1) = x+ v(1).*v(2).*(1-x/5);
dv(2) = v(1);

script M-file shooting.m


%Shooting Method for Nonlinear ODE
D = 1;
Intv = [1 3];

% First Try
G1 = -1; % 1
init=[G1 2];
[x,y]=ode45('myode4',intv,init);
[a b]=size(y);

Ordinary Differential Equations 127


R1=y(a,2); % 1
% Second Try
G2=-5; % 2
init=[G2 2];
[x,y]=ode45('myode4',intv,init);
[a b]=size(y);
R2=y(a,2); % 2

while abs(y(a,2)-D)>1e-6 %
1E-6
G=G1+(G2-G1)*(D-R1)/(R2-R1); %
init=[G 2];
G1=G2; % 1
G2=G; %
[x,y]=ode45('myode4',intv,init);
[a b]=size(y);
R1=R2; % 1
R2=y(a,2); %
P=abs(y(a,2)-D); % loop
fprintf('Now your error is %10.6f \n',P)
end % loop plot
%
m=plot(x,y);
legend(m,'dy','y')

% *************************************************** END *******

run file shooting


shooting
Now your error is 1.207074
Now your error is 2.396240
Now your error is 0.568361
Now your error is 0.249510
Now your error is 0.045735
Now your error is 0.003186
Now your error is 0.000039
Now your error is 0.000000

MATLAB error
10-6 MATLAB

128 Ordinary Differential Equations


2
dy
1.5 y

0.5

-0.5

-1

-1.5

-2

-2.5

-3
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3

Boundary Value Problems Shooting Method


Finite Difference Method

Numerical Method

"
(The Excact Solution of Boundary
Layer Theory)

(Boundary Layer)



Ordinary Differential Equations 129




Navier-Stokes Equation

2 f + ff = 0

Blasius Equation H. Blasius


1908
Prandtl 1904

= f ( )
u
U

u
U
f = df ()
d
U
= y
x

kinematic viscosity
x
y


potential flow viscous
flow Blasius Equation Boundary condition
F :
= 0 f = 0 = 0 f = 0

F :
, f = 1

130 Ordinary Differential Equations


Blasius Equation third order ordinary differential equation boundary value problem Runge
- Kutta Method Shooting Method
M-file shooting method
M-file integrand system of first order ODE
function xdot = blas(t,x)
xdot = zeros(3,1);
xdot(1) = -x(3).*x(1)/2;
xdot(2) = x(1);
xdot(3) = x(2);

infinity
infinity
f 1

program shooting method 6 , f = 1 M-file


D=1;
Intv=[0 6];

% **************
G1=1;
init=[G1 0 0];
[x,y]=ode45('blas',intv,init);
[a,b]=size(y);
R1=y(a,2);
G2=2;
init=[G2 0 0];
[x,y]=ode45('blas',intv,init);
[a,b]=size(y);
R2=y(a,2);

% **************
while abs(y(a,2)-D)>1e-6
G=G1+(G2-G1)*(D-R1)/(R2-R1);
init=[G 0 0];
G1=G2;
G2=G;
[x,y]=ode45('blas',intv,init);
[a,b]=size(y);
R1=R2;
R2=y(a,2);
P=abs(y(a,2)-D);
fprintf('Now your error is %10.6f \n',P)
end
m=plot(x,y);
legend(m,'d2y','dy','y',0)

Now your error is 0.526004


Now your error is 0.249148

Ordinary Differential Equations 131


Now your error is 0.037440
Now your error is 0.002332
Now your error is 0.000023
Now your error is 0.000000

4.5
d2y
4 dy
y

3.5

2.5

1.5

0.5

0
0 1 2 3 4 5 6


99%
= y @ u = 0.99U

u
U
= f ( ) f = 0.99
interpolation run M-file shooting
shooting
Now your error is 0.514670
Now your error is 0.238315
Now your error is 0.033354
Now your error is 0.001918
Now your error is 0.000016
Now your error is 0.000000

ODE MATLAB
a=y(:,2);
b=interp1(a,x,0.991,'spline')
b =
4.9654

132 Ordinary Differential Equations


= 4.9654
U
x

Reynolds Number, Re x = Ux

=
Ux


4.965x
=
Re x

Ordinary Differential Equations 133


9 MATLAB GRAPHICS

2 plot MATLAB
plot plot x, y 2

9.1 plot 2
plot x, y plot

n Error Bar
error bar
errorbar(x,y,e,str)
plot(x,y) error bar e
coordinate plot x-y str option
character string x,y
errorbar(x,y,l,u) error bar (xi , yi ) yi
li yi ui

x = linspace (0,15,40);
y = exp(cos(x)) ;
delta = 0.1*y ;
errorbar (x,y, delta)

134 MATLAB Graphics


3

2.5

1.5

0.5

0
-2 0 2 4 6 8 10 12 14 16

o Graph Function
function file plot function Function
MATLAB fplot
fplot (function, lim, str, tot)
plot function function ( function file function.m)
lim vector Limit function plot
2 lim = [xmin xmax] minimum
maximum x lim = [xmin xmax ymin ymax]
option str
tot relative error tot

lim = [1 0];
fplot(exp(x),lim)

MATLAB Graphics 135


4
x 10
2.5

1.5

0.5

0
1 2 3 4 5 6 7 8 9 10

p Polar Plot
plot polar coordinate polar

polar(q,r) plot polar coordinate q vector q


radian vector r

theta = linspace(0,2*pi,200);
r = sqrt(abs(sin(theta)).*abs(cos(theta)));
polar(theta,r)

option string ,
plot

90
0.8
120 60
0.6

150 0.4 30

0.2

180 0

210 330

240 300
270

136 MATLAB Graphics


q Plot Complex Plane
complex number z = x + iy plot complex plane
X, Y, Z matrix x,y vector

quiver(X,Y) coordinate xij, yij


quiver(X,Y,dx,dy) coordinate xi, yi argument dx magnitude dy
quiver(X,Y,Dx,Dy) coordinate xij, yij argument magnitude dxij, dyij

feather(Z,str) magnitude argument element
complex matrix Z x option string
str option
feather(x,y) feather (x+y * i) i = 1
compass(z,str) (0,0) magnitude argument
element complex matrix Z str option

compass(x, y) compass (x+y*i) i = 1
rose(v,n) argument histogram frequency arguments vector v
n option MATLAB
n = 36

plot complex plane


z =
1.0000+2.0000i 2.0000+1.0000i 2.0000
5.0000 4.0000-2.0000i 0+4.0000i
3.0000-4.0000i 0+1.0000i 4.0000-1.0000i

subplot(2,2,1)
quiver(real(z),imag(z))
title('quiver')

subplot(2,2,2)
feather(real(z),imag(z))
title('feather')

subplot(2,2,3)
compass(real(z),imag(z))
title('compass')
x=[1 2 1 3 4 5 3 2 3 4 4 1 6 7];

MATLAB Graphics 137


subplot(2,2,4)
rose(x)
title('rose')

plot
quiver feather
4 4

3 2

2 0

1 -2

0 -4
1 2 3 4 0 5 10 15

compass rose
90 5 90 4
120 60 120 60
2.5 2
150 30 150 30

180 0 180 0

210 330 210 330

240 300 240 300


270 270

r Histogram Bar Graphs


Histogram
MATLAB histogram
his(x,n) histogram vector x n option
MATLAB
n = 10

bar graph
bar(x) bar graph x
bar(x,z) bar graph x vector z

stairs(x) stairs graph x (stairs graph bar graph )
stairs(x,z) stairs graph x vector z

138 MATLAB Graphics


stem(x) stem graph x stem graph bar graph


stem(x,z) stem graph x vector z

bar graph histogram


x=[1 2 3 5 4 2 3 1 4 5 3 2 2 3 1 5 6];

x
subplot(2,2,1)
hist(x)
title('Histogram')
subplot(2,2,2)
bar(x)
title('Bar Graph')
subplot(2,2,3)
stem(x)
title('Stem Graph')
subplot(2,2,4)
stairs(x)
title('Stairs Graph')

Histogram Bar Graph


4 6

3
4
2
2
1

0 0
0 2 4 6 0 5 10 15 20

Stem Graph Stairs Graph


6 6

5
4
4

3
2
2

0 1
0 5 10 15 20 0 5 10 15 20

MATLAB Graphics 139


s Comet Plot
Comet plot Plot
plot

comet(x,y) vector x y
pie(x) vector x
element
element vector x
pie(x,y) vector x
element x vector y x
0 1 element y 1 element
x
pie(x,condition) condition

comet plot plot


pie3(x)
pie(x) 3
x=[15 20 14 12 15]';
y=[0 1 0 0 0]';
txt=['Jan'; 'Feb';'Mar';'Apl';'May'];
pie(x,y);
legend(txt)

140 MATLAB Graphics


Jan
20% 20% Feb
Mar
Apl
May

16%

26%

18%

9.2 3
MATLAB 3
MATLAB 3
(mesh) 3
plot 3 MATLAB

n Plot 3
plot coordinate (x,y,z) Cartesian Coordinate
plot3

Plot3(x,y,z) x, y ,z vector plot coordinate (xi, yi,


zi) parameter x, y, z Matrix
MATLAB plot column parameter
vector column
Plot3(x,y,z,str) str

plot

Title, xlabel, ylabel, zlabel, text plot


2 z = sin (x) - cos (y) x y 0 2

MATLAB Graphics 141


x = linspace (0, 2*pi, 100) ;
y = x ;
z = sin (x).* cos (y) ;

plot3(x,y,z)
xlabel('X')
ylabel('Y')
zlabel('Z')
title(' 3-D Plot')

3-D Plot

0.5

0
Z

-0.5
8
6 8
4 6
4
2
2
Y 0 0
X

o 3
3
z = f (x,y)

plot plot3 zi = f(xi,


yi)

zij = f(xi,yj)

x vector m y vector n
plot m x n plot3 m n plot m

142 MATLAB Graphics


grid grid
plot grid
[u,v] = meshgrid(x,y) x vector m y vector n
vector
matrix u v n x m matrix
x y coordinate rectangular domain
coordinate (uij , vij) zij = f (uij,vij)
[x,y,z] = cylinder(r,n) grid cylindrical coordinate vector r
r
coordinate r
n
n = 20
r r = [ 1 1 ]
[x,y,z] = sphere(n) spherical grid matrix x, y, z x, y
z (n+1) * (n-1)
grid function MATLAB
function
grid x = [ 1 2 3 ] y = [ 4 5 ] plot
coordinate z zij = f(xi,yj) (xi,yj) (1,4), (2,4), (3,4), (1,5),
(2,5), (3,5) meshgrid [u v] = meshgrid (x,y)
x=[1 2 3];
y=[4 5];
[u v]=meshgrid(x,y)
u =
1 2 3
1 2 3
v =
4 4 4
5 5 5

zij = f (xij,yij)

p
mesh, meshc, meshz waterfall

MATLAB Graphics 143


mesh(X,Y,Z,C) plot (xij, yij, zij) matrix X,Y,Z m x n
C matrix
C option
MATLAB C = Z
mesh(x,y,Z,C) x vector m y vector n
Z matrix m x n MATLAB plot (xi,
yj, zij ) MATLAB meshgrid vector x
y C option
mesh(Z) plot (i, j, zij) z matrix
meshc(...) mesh (...) contour curve
meshz(...) mesh (...) grid x y
z
waterfall(...) meshz(...) grid
hidden on MATLAB mesh
hidden off MATLAB mesh
hidden hidden on off MATLAB
hidden on

mesh function

z = sin (x) cos(y)

x y 0 2
script file
x = linspace(0,2*pi,40); % x vector 1 x 100
y = x; % y vector 1 x 100
z = sin(x)*cos(y); % z [100 x 1] x [1 x 100] = [100 x 1]
subplot(2, 2, 1);
mesh(x, y, z);
title('Mesh Plot')

subplot(2, 2, 2);
meshc(x, y, z) ;
title('Meshc Plot')

144 MATLAB Graphics


subplot(2, 2, 3)
meshz(x, y, z)
title('Meshz Plot')

subplot(2, 2, 4)
waterfall(x, y, z)
title('Waterfall')

(x,y) , (y,z) (z, x) 3


gird off
x, y, z axis off plot 2

q
mesh
MATLAB
mesh

surf(X,Y,Z,C) parameter X, Y, Z C matrix m x n


plot (xij, yij, zij) cij
C C = Z x y vector
plot (xi , yi , zij )

MATLAB Graphics 145


surfc(x,y,z,c) surf(...) MATLAB contour

surfl(x,y,z,ls) surf(...)
vector ls = [ u h ] u (x,y) x
h (x,y)

surfnorm(x,y,z) surf(...) normal vector
x y z matrix
vector x y surf(...)
[Nx,Ny,Nz] = surfnorm(x,y,z)
surfnorm (x, y, z) normal
vector (xij, yij , zij) (nxij , nyij , nzij )

3 surf mesh
MATLAB shading 3

shading faceted MATLAB



mesh
shading flat faceted mesh
shading interp interpolated mesh

interpolate

surf
x = linspace(0,2*pi,40); y = x; z = sin(x)'*cos(y);

subplot(2,1,1);
surf(x,y,z);shading interp
axis off
title('Surface Plot')

subplot(2,1,2)
[u v]=meshgrid(x,y);
surfnorm(u,v,z);shading flat
axis off

146 MATLAB Graphics


title('Surface Plot with Normal Line')

r
3
view

view(az,el) azimuth, az elevation, el


azimuth (x,y) x
elevation (x,y)
az el

view(x,y,z) x, y, z Cartesian
MATLAB x, y, z
vector
view(2) 2 (az = 0, el = 0)
view(3) 3 (az = -37.50, el = 30)
[a,b]= view a az b el

MATLAB Graphics 147


s Contour Line
contour line
contour
contour line

contour(Z) contour matrix Z Z m x n, MATLAB


scale x 1 m y 1 n
contour(Z,n) contour line matrix Z n n
MATLAB n = 10
contour(x,y,z) contour line x,y scale x
y x,y rector (xi,yij,zij)
contour(...,str) contour line str string
C = contour(...) matrix C label contour
contourf(...) contour plot
clabel(C) lable contour C
C = contour(...) MATLAB

help clabel
contour3(...) contour line 3

148 MATLAB Graphics


contour
x = linspace(0,2*pi,40); y = x; z = sin(x)'*cos(y);
C = contour(z);
clabel(C);

40
-0.2
-0.4 0.4

35 0.8
-0.2

30 -0.8 -0.8
-0.4
0.6 0 -0.6
25 -0.6 0
0.2

20 -0.2 0
0.2
-0.4 0.4
0.6 0.6
15 0
-0.6

10 -0.8
0.8 0.4 0.2
5

5 10 15 20 25 30 35 40

bar3(y,Z) columns m x n matrix Z bars 3


vector y y element

bar3(Z) y =1:m Z m x n
bar3(y,Z,w) w > 1
w = 0.8
bar3(...,'detached')

bar3(...,'grouped')
bar3(...,'stacked')
bar3(...,linespec) string

MATLAB Graphics 149


stem 3

Stem3(z) discrete surface z stems x-y


2
Stem3(x,y,z) surface z x,y
Stem3(...,'filled') stem
Stem3(...,linespec) plot

3
x = 3 2 5 7 9 6 4 8 4 10]';
y = 2*x-3;
z = y*x';
bar3(z)

stem
x=[3 2 5 7 9 6 4 8 4 10]';
y=2*x-3;
z=y*x';
stem3(x,y,z)
xlabel('This is x')
ylabel('This is y')
zlabel('This is z')

150 MATLAB Graphics


200

150
This is z

100

50

0
20
15 10
10 8
6
5
4
This is y 0 2
This is x

9.3
MATLAB function

MATLAB
3 -- Red-Green-Blue (RGB) Color RGB color (0, 0, 0)
RGB color (1 , 1, 1) RGB
RGB
0 1
MATLAB (color map)
plot color map matrix m x 3 row 3 RGB color
matrix m
MATLAB color map MATLAB
MATLAB m color map

shading shading interp

MATLAB Graphics 151


interpolate color map matrix color map

colormap(map) color map map map MATLAB


map M-file
color map
colorbar plot
colorbar(horiz) plot

color map MATLAB 11 map ( map


) colormap(map) colormap map map

gray gray linear scale


hsv Hsv-Saturation-Value color map

hot ---
cool -
bone - X - ray
copper
flag - -
pink
prism -
jet hsv color map
white
lines Color Map
colorcube color-cube
summer
autumn
winter
spring

colormap ( map)

152 MATLAB Graphics


map(m) map map m
matrix m x 3


x = linspace(0,2*pi,40);
y = x;
z = sin(x)'*cos(y);
surf(x,y,z);
colormap gray
colorbar
title('Surface Plot with Color Bar')

9.4
MATLAB function


MATLAB function frame
movie
movie frame frame figure window
plot frame

MATLAB Graphics 153


frame

M = moviein(n) M MATLAB frame


column Matrix M n frame

frame
M(n,j) = getframe frame j figure window
frame

movie(M) M 1
movie(M,n) M n
movie(M,n,FPS) M n FPS frame
FPS MATLAB 12 frame
MATLAB
FPS

ZORO frame 20 frame


M-file
n = 20;
ZORO = moviein(n)
for j = 1:n
plot
ZORO(:,j) = getframe
end
movie(ZORO)

MATLAB version 5.3 6


moviein(n) getframe
MATLAB version 6

n = 20;

154 MATLAB Graphics


for j = 1:n
plot
ZORO(:,j) = getframe
end
movie(ZORO)

format format

MATLAB plot
plot
fixed a
= axis [xmin,xmax,...] plot axis(a), axis(axis)
plot axis a

frame
frame

Windows multi-tasking

cpu
MATLAB
frame-per-second

"
n Flow Pass Rotating Cylinder
2 stream line
stream function contour line
stream line stream function
potential flow doublet
vortex


stream function

MATLAB Graphics 155


a2
= Ur sin + ln( r )
r 2

a, K U

M-file a =2 2aU
=K
circulation 4 K= 0
K
M-file

% M-file for Potential Flow


% Flow Pass Rotating Cylindera=2;
r=linspace(a,20);
zeta=linspace(0,4*pi);
r=r';zeta=zeta';
[r zeta]=meshgrid(r,zeta);

K=0;
phi=sin(zeta)*(r./a - a./r)-K*log(r/a);
[x y]=pol2cart(zeta,r);
co= [-150 -100 -75 -50 -25 -10 -1 -0.1 0.1 1 10 25 50 75 100 150];
subplot(2,2,1)
contour(x,y,phi,co,'b'); %
axis equal
axis off
axis([-6 6 6 6])

K=100;
phi=sin(zeta)*(r./a a./r)-K*log(r/a);
[x y]=pol2cart(zeta,r);
co=[-150 100 75 50 25 10 1 0.1 0.1 1 10 25 50 75 100 150];
subplot(2,2,2)
contour(x,y,phi,co,'b');
axis equal
axis off
axis([-6 6 -6 6])

K=200;
phi=sin(zeta)*(r./a - a./r)-K*log(r/a);
[x y]=pol2cart(zeta,r);
co= [-300 -250 -150 -100 -75 -50 -25 -10 -1 -0.1,...
0.1 1 10 25 50 75 100 150];
subplot(2,2,3)
contour(x,y,phi,co,'b');
axis equal
axis off
axis([-6 6 -6 6])

K=300;
phi=sin(zeta)*(r./a - a./r)-K*log(r/a);
[x y]=pol2cart(zeta,r);
co= [-400 -300 -250 -200 -150 -100 -80 -75 -65 -60,...
-40 -30 -1 5 10 25 35 50 60 75];

156 MATLAB Graphics


subplot(2,2,4)
contour(x,y,phi,co,'b');
axis equal
axis off
axis([-6 6 -6 6])

o Plot Velocity Vector


potential flow velocity vector
Rankine body stream function

q 2ay
= Uy tan 1 2
2 x + y2 a 2

potential flow Vx =
y
Vy =

x

gradient stream function
stream line velocity vector
contour plot stream lines
x y gradient
velocity vector quiver

M-file
% Stream Line Plot With Velocity Vector
a=2;

MATLAB Graphics 157


r=linspace(a^2,10);
q=linspace(0,2*pi);
r=r';q=q';
[x y]= pol2cart(q,r);
[x y]= meshgrid(x,y);
phi=0.8*y-(atan2(2*a*y,(x.^2+y.^2-a^2)));
contour(x,y,phi,20,'r'); % stream line
axis equal
hold on
grid off
phi0=[-0.01 0 0.01];
contour(x,y,phi,phi0,'r') % stream line body
x=linspace(-7,7,10);
y=linspace(-4,4,10);
x=x';y=y';
[x y]=meshgrid(x,y);
a=2;
phi=0.8*y-(atan2(2*a*y,(x.^2+y.^2-a^2)));
[v u]=gradient(phi,0.2,0.2); % velocity
v=-v;
u=abs(u);
quiver(x,y,u,v,0.6) % velocity vector
hold off
axis off

Response Surface
single DOF damped forced vibration
2 function frequency ratio damping ratio

158 MATLAB Graphics



Normalize Magnitude 1
normalized magnitude 1


damping ratio

MATLAB Graphics 159


10 SYMBOLIC MATHEMATICS

MATLAB
MATLAB toolbox Symbolic Mathematics
Symbolic Math Toolbox
MATLAB Toolbox Student Edition MATLAB MATLAB 5.x
version
MATLAB 5.x Symbolic
Toolbox MATLAB 5.x
Symbolic Mathematics
sin(x) x
sin(x) symbolic mathematic x
function sin(x) sin(x) d sin( dx
x)
=
cos(x)
Symbolic Math Toolbox symbolic function MATLAB
Maple V. Software Package software symbolic mathematic

University of Waterloo Watterloo Maple
Software, Inc. Canada

10.1 Symbolic Algebra


n Symbolic Expression

Symbolic expression quote make


t = x^2+5*x-4

expression t(x) expression 1


sin(y+x) x y
independent variable

160 Symbolic Mathematics


indepandent variable MATLAB expression 1
( i j ) x x MATLAB
2 () MATLAB x
( x ) independent variable MATLAB
expression independent variable function symvar

symvar(exp(x)) MATLAB independent variable symbolic expression exp

variable
symbolic variable / symbolic expression MATLAB
symbolic variable sym

S=sym(expression) symbolic variable S expression expression



symbolic variable expression

x=sym(x)

x symbolic variable x
x symbolic expression
f=x^2+3*x-5;
g=2*x^2-5*x+2;

f g symbolic expression
syms symbolic variable
syms ex1 ex2... symbolic variable expressions expression

x, y z symbolic variable
syms 'x' 'y' 'z'

sym(x); sym(y); sym(z);

Symbolic Mathematics 161


findsym

findsym(S) symbolic variable S S sym

s=sym('exp(bc)*sin(z)');
findsym(s)
ans =
bc, z

bc z symbolic variables expression


x=sym('x');
f=5*x^2-3*x-1;
findsym(f)
ans =
x

f symbolic expression symbolic variable x expression


symbolic expression class
class(OBJ) OBJ

double double precision floating point

number MATLAB
sparse 2-D real (or complex) sparse matrix

struct Structure array 12

cell cell array 12


char Character String
sym symbolic variable

x=sym('x');
class(x)
ans =
sym

f=5*x^2-3*x-1;
class(f)
ans =
sym

o plot symbolic expression


ezplot plot
1. plot 2

162 Symbolic Mathematics


ezplot(s) plot symbolic expression s function
plot 2 2
ezplot symbolic variable

ezplot(s,[min max]) plot independent variable S min max

p Expression
expression function function

collect(s) expression S

collect(s,v) collect(s) v independer variable
expand(s) expression s
factor(s) expression s
simple(s) s
simplify(s) s Maple

function expression
x=sym(x)
s1= x^2-4*x+4;
s2=(x*cos(x))^2-x^2;
s3=(x-3)*(x-6)*(x+2)/(x^2-4*x-6);

factor(s1)
ans =
(x-2)^2

expand(s2)
ans =
x^2*cos(x)^2-x^2

factor(s2)
ans =
x^2*(cos(x)-1)*(cos(x)+1)

collect(s3)
ans =
(x-3)*(x-6)*(x+2)/(x^2-4*x-6)

expand(s3)
ans =
1/(x^2-4*x-6)*x^3-7/(x^2-4*x-6)*x^2+36/(x^2-4*x-6)

Symbolic Mathematics 163


simple(s3)
ans =
(x^3-7*x^2+36)/(x^2-4*x-6)

symbolic expression MATLAB



q Operations on Symbolic expression
operation symbolic expression symbolic function
symbolic function symbolic expression
function
numden(s) expression 2 symbolic expression s
numeric(s) s
double(sym(s))
poly2sym(c) polynomial coefficient vector c symbolic expression
pretty(s) s output
sym2poly(s) s polynomial coefficient vector
symadd(s1,s2) symbolic expression, s1 + s2 sym(s1)+sym(s2)
s1+s2
symmul(s1,s2) symbolic expression, s1 x s2 sym(s1)*sym(s2)
s1*s2

sympow(s1,s2) symbolic expression, s1^s2 sym(s1)^sym(s2)


s1^s2
symsub(s1,s2) symbolic expression, s1 - s2 sym(s1)-sym(s2)
s1-s2

function s1,s2 s3 symbolic expression

x = sym(x)
s1= x^2-4*x+4');
s2= (x*cos(x))^2-x^2
s3= (x-3)*(x-6)*(x+2)/(x^2-4*x-6)
[s4 s5]=numden(s3)
s4 =
(x-3)*(x-6)*(x+2)
s5 =
x^2-4*x-6
sym2poly(s4)
ans =
1 0 0 36

s4 + s5

164 Symbolic Mathematics


ans =
(x-3)*(x-6)*(x+2)+x^2-4*x-6

factor(ans)
ans =
x^3-6*x^2+30-4*x

10.2 Equation Solving


n
MATLAB symbolic expression

solve(s) expression s variable s


s symbolic equation s
solve(s1,s2,...,sn) n s1,s2 sn independent variable
symbolic equation s1, s2,...sn

solve(s)
syms x1 y1 z1
s1= x1+y1+z1-5;
s2= 2*x1-y1+2*z1-4;
s3= x1-4*y1-z1+2;
a=solve(s1)
a =
-y1-z1+5

symbolic expression MATLAB x


independent variable s1, s2, s3

[x y z]=solve(s1,s2,s3)
x =
9/2
y =
2
z =
-3/2

x = 9/2, y = 2 z = -3/2 x,y z



class(x)
ans =
sym

Symbolic Mathematics 165


x symbolic variable
double

double(x) x expression
double precession number

x
double(x)
ans =
4.5000

symbolic MATLAB
analytical solution MATLAB numerical solution
S1=sym('x^3*exp(x)*sin(x))=2');
[b]=solve(s1)
b =
.2539413645466444913948333 1.040276743255826267579410*i

o Solution to ODE
first-order-ODE

dy
y' = = g( x, y)
dx

ODE symbolic toolbox


first-order ODE
dsolve(equation,condition)
ODE symbolic
equation option condition initial

condition independent variable MATLAB


symbolic t dy MATLAB Dy D
dt
differential dependent variable
dz dt
= sin x MATLAB
Dz=sin(x) second derivative D2y third derivative

166 Symbolic Mathematics


D3y condition
MATLAB C1, C2,... integrate

first order 1
dsolve('Dx = -a*x^2')
ans =
1/(a*t+C1)

x = dsolve('Dx = -a*x^2','x(0) = 1','s')


x =
1/(a*s+1)

x = dsolve('Dx = -a*x^2','x(0) = 1')


x =
1/(a*t+1)

first order
dsolve(equation1, equation2,...,condition)
dsolve(equation1, equation2,...,condition)

S = dsolve('Df = f + g, Dg = -f + g','f(0) = 1','g(0) = 2')


S =
f: [1x1 sym]
g: [1x1 sym]

2 output S MATLAB
field S.f S.g (
MATLAB 5 12)
field
S.f
ans =
exp(t)*cos(t)+2*exp(t)*sin(t)

S.g
ans =
-exp(t)*sin(t)+2*exp(t)*cos(t)

first order 3
[u1 v1 w1] = dsolve('Du=v, Dv=w, Dw=-u','u(0)=0, v(0)=0, w(0)=1')
u1 =
1/3*3^(1/2)*exp(1/2*t)*sin(1/2*t*3^(1/2))-
1/3*exp(1/2*t)*cos(1/2*t*3^(1/2))+1/3*exp(-t)

Symbolic Mathematics 167


v1 =
1/3*3^(1/2)*exp(1/2*t)*sin(1/2*t*3^(1/2))+
1/3*exp(1/2*t)*cos(1/2*t*3^(1/2))-1/3*exp(-t)
w1 =
1/3*exp(-t)+2/3*exp(1/2*t)*cos(1/2*t*3^(1/2))

order
nonlinear second order ODE

d2y dy
2
= y 5
dx dx

initial condition y (0) = 0

y(0) = 0.25

dsolve('D2y=y-Dy-5','Dy(0)=0,y(0)=0.25')
ans =
5+(-19/8-19/40*5^(1/2))*exp(1/2*(5^(1/2)-1)*t)-19/40*(5^(1/2)-
1)*5^(1/2)*exp(-1/2*(5^(1/2)+1)*t)

analytical solution MATLAB

10.3 Differentiation Integration


differentiation Integration symbolic math function

diff(s) differentiation expression s independent variable


diff(s,t) differentiation expression s independent variable t
diff(s,n) differentiation expression s independent variable
n
diff(s,t,n) differentiation expression s t n

symbolic toolbox function diff numerical diff function


MATLAB symbolic numeric variable

Numeric Integration function

int(s) integrate symbolic expression s independent variable


int(s) integrate symbolic expression s independent variable t
int(s,a,b) integrate s independent variable limit a b

168 Symbolic Mathematics


int(s,t,a,b) integrate expressions t a b
int(s,m,n) integrate expression s independent variable
limit m n symbolic variable

function integrate
integrate symbolic MATLAB
numerical integration

Symbolic differentiation integration


x=sym(x);
s1=x^3*exp(x)*sin(x)-2;
s2=x^3+3*x^2+5*x-2;
s3=x*sin(x);

diff(s1)
ans =
3*x^2*exp(x)*sin(x)+x^3*exp(x)*sin(x)+x^3*exp(x)*cos(x)

diff(s1,'x')
ans =
3*x^2*exp(x)*sin(x)+x^3*exp(x)*sin(x)+x^3*exp(x)*cos(x)

diff(s1)
ans =
3*x^2*exp(x)*sin(x)+x^3*exp(x)*sin(x)+x^3*exp(x)*cos(x)

diff(s1,'t')
ans =
0

diff(s2)
ans =
3*x^2+6*x+5

diff(s3,3)
ans =
-3*sin(x)-x*cos(x)

integrate
int('x^4')
ans =
1/5*x^5

int('x*cos(x)')
ans =
cos(x)+x*sin(x)

Symbolic Mathematics 169


int('x^2*exp(x)')
ans =
x^2*exp(x)-2*x*exp(x)+2*exp(x)

int('x*sin(x)',0,pi)
ans =
pi
int('x^2/sin(x)')
ans =
int(x^2/sin(x),x)

MATLAB integrate

10.4 Symbolic Transformation


transformation function
Fourier Transform Laplace Transform Symbolic Toolbox transformation

n Laplace Transform
Laplace Transform function f(t) time domain function L(s) s-domain
transformation

f (t )e
st
L ( s) = dt
0

Laplace Transform differential equation


Control System MATLAB laplace

L = laplace(F,var1,var2)
Laplace transform symbolic expression F var1-
domain function var2-domain
L(var2) transform F(var1) option var1,
var2 MATLAB var1 t var2 s
F, var1 var2 sym
sym
f = ilaplace(L,var1,var2)
inverse Laplace transform symbolic expression L
L option var1 var2 t s
f(var2) inverse transform L(var1) F,

170 Symbolic Mathematics


var1 var2 sym
sym

Laplace transform

f (t ) = 5e 2 at cos t

MATLAB
syms a s t w
f=5*exp(-2*a*t)*cos(w*t);
L=laplace(f,t,s)
L =
5*(s+2*a)/((s+2*a)^2+w^2)
ilaplace(L,s,t)
ans =
5*exp(-2*a*t)*cos(w*t)

o Fourier Transform
function function
function time-domain frequency-domain
Fourier Transform

F ( ) = f ( t )e
jt
dt

transform frequency-domain time-domain Inverse Fourier Transform


f (t) = F ( ) e
jt
dt

MATLAB symbolic Fourier transform


F = fourier(f, var1, var2 )
Fourier transform symbolic f
independent variable x function
w. independent
variable var1 var2
f = ifourier(F,var1,var2)

Symbolic Mathematics 171


inverse Fourier transform symbolic F
independent variable w
function x
independent variable var1 var2

syms x t
fourier(exp(-x^2),x,t)
ans =
pi^(1/2)*exp(-1/4*t^2)

f=ifourier(F,t,x)
f =
1/2*4^(1/2)*exp(-x^2)

simple(f)
ans =
exp(-x^2)

Fourier Transform function 2 function Step function u(t)


Impulse function (t) Step function
Ku(t-a) = 0 t < 0
Ku(t-a) = a t > 0
impulse function
K ( t a ) = 0 for t a

K ( t a) dt = K

for t = a

MATLAB function function


Step function Heaviside(t) Impulse function Dirac(t)
function

p Z-Transform
transform transform function
discrete-time domain Z-transform

F ( z) = f ( n) z
n=0
n

z complex MATLAB function ztrans iztran Z-transform inverse Z-


transform

172 Symbolic Mathematics


F=ztrans(f,var1,var2) Z-transform symbolic function f
independent variable n F
function z
var1 var2
f=iztran(F,var1,var2) inverse Z-transform symbolic function F
independent variable z f
function n
var1 var2

syms k n w z
ztrans(2^n)
ans =
z/(z-2)

iztrans(ans)
ans =
2^n

F=ztrans(cos(n*k),k,z)
F =
z*(-cos(n)+z)/(-2*z*cos(n)+z^2+1)

F=ztrans(cos(n*k),n,w)
F =
w*(-cos(k)+w)/(-2*w*cos(k)+w^2+1)

f=iztrans(exp(x/z),z,k)
f =
x^k/k!

F=ztrans(f,k,z)
F =
exp(x/z)

10.5 Function Calculator


symbolic toolbox M-file file function
function symbolic toolbox
function calculator funtool
funtool figure windows 3

Symbolic Mathematics 173


1 function f(x) 2 function g(x)
3 function f(x), g(x)
function f(x) 3
n 1
1
1. function f(x) MATLAB expression
Enter MATLAB f(x)
1
2. function g(x) MATLAB expression
Enter MATLAB g(x)
2
3. x x
[xmin , xmax ] xmin xmax x
4. parameter a function
parameter f(x) g(x) parameter a
a f(x) g(x)

o 2

174 Symbolic Mathematics


2 function 1
function f(x) f(x)
2 4

1 f(x)
f(x)


df/dx f(x)
int f f(x)
simple f f(x) ()
f(x) f(x)
num f

f(x) f(x)
den f

1/f f(x) 1/f(x)
finv f(x) inverse function

inverse function function

2 function f(x) parameter a



f +a f(x) f(x) + a
f -a f(x) f(x) - a
f *a f(x) f(x) * a
f / a f(x) f(x) / a
f^a f(x) f(x) ^ a
f(x+a) f(x) f(x + a)
f(x*a) f(x) f(x * a)

Symbolic Mathematics 175


3 f(x) g(x) function operation


f +g f(x) f(x) + g(x)
f g f(x) f(x) - g(x)
f *g f(x) f(x) * g(x)
f /g f(x) f(x) / g(x)
f(g) f(x) f(g(x))
g =f g(x) f(x)
swap f(x) g(x)

4 Function Calculator
function f(x) list funtool
f(x) function file fxlist
fxlist function function

 Insert f(x) list
 Cycle f(x) f(x) list
 Delete function f(x) list ( list)

 Reset f, g, x, a and fxlist


 Help funtool
 Demo funtool
 Close

funtool

funtool function
MATLAB Graphics User Interface (GUI)
mouse MATLAB

176 Symbolic Mathematics


GUI GUI
2

10.6 Symbolic Math Toolbox : Student Edition


Symbolic Math Toolbox Version 2.0 version Student Edition
.. 1997 version
symbolic toolbox

help

Calculus.
diff Differentiate.
int Integrate.
limit Limit.
taylor Taylor series.
jacobian Jacobian matrix.
symsum Summation of series.

Linear Algebra.
diag Create or extract diagonals.
triu Upper triangle.
tril Lower triangle.
inv Matrix inverse.
det Determinant.
rank Rank.
rref Reduced row echelon form.
null Basis for null space.
colspace Basis for column space.
eig Eigenvalues and eigenvectors.
svd Singular values and singular vectors.
jordan Jordan canonical (normal) form.
poly Characteristic polynomial.
expm Matrix exponential.

Simplification.

Symbolic Mathematics 177


simplify Simplify.
expand Expand.
factor Factor.
collect Collect.
simple Search for shortest form.
numden Numerator and denominator.
horner Nested polynomial representation.
subexpr Rewrite in terms of subexpressions.
subs Symbolic substitution.

Solution of Equations.
solve Symbolic solution of algebraic equations.
dsolve Symbolic solution of differential equations.
finverse Functional inverse.
compose Functional composition.

Variable Precision Arithmetic.


vpa Variable precision arithmetic.
digits Set variable precision accuracy.

Integral Transforms.
fourier Fourier transform.
laplace Laplace transform.
ztrans Z transform.
ifourier Inverse Fourier transform.
ilaplace Inverse Laplace transform.
iztrans Inverse Z transform.

Conversions.
double Convert symbolic matrix to double.
poly2sym Coefficient vector to symbolic polynomial.
sym2poly Symbolic polynomial to coefficient vector.
char Convert sym object to string.

Basic Operations.

178 Symbolic Mathematics


sym Create symbolic object.
syms Short cut for constructing symbolic objects.
findsym Determine symbolic variables.
pretty Pretty print a symbolic expression.
latex LaTeX represention of a symbolic expression.
ccode C code represention of a symbolic expression.
fortran Fortran represention of a symbolic expression.

Special Functions.
sinint Sine integral.
cosint Cosine integral.
zeta Riemann zeta function.
lambertw Lambert W function.

String handling utilities.


isvarname Check for a valid variable name.
vectorize Vectorize a symbolic expression.

Pedagogical and Graphical Applications.


rsums Riemann sums.
ezplot Easy to use function plotter.
funtool Function calculator.

Demonstrations.
symintro Introduction to the Symbolic Toolbox.
symcalcdemo Calculus demonstration.
symlindemo Demonstrate symbolic linear algebra.
symvpademo Demonstrate variable precision arithmetic
symrotdemo Study plane rotations.
symeqndemo Demonstrate symbolic equation solving.

Symbolic Mathematics 179


11 M-BOOK

11.1 M-book
word processing


word processing
copy

word
processing

word processing
word processing
M-book
M-book 2 Microsoft Word for Window
program word processing program word processing
MATLAB
Word Word
MATLAB background
Word MATLAB
program M-book Save file Word document file (.doc)

M-book ( Window 95 system)


MATLAB 4 MATLAB 5
Microsoft Word for Window 6.0 7.0

180 M-book
Word 97 Math Works MATLAB
5.0 download file Internet
www.mathworks.com MATLAB 5.1 Word 97
Word MATLAB
MATLAB MATLAB directory Word
template
M-book template Word Word
template Word template
Normal.dot MATLAB Word template M-book.dot
template Word MATLAB macro

11.2
Word MATLAB M-book Word
Word template Normal.dot document file M-
book
file Word

file New File Menu New dialog box

M-book template Word document file


Word MATLAB

 file file M-book

MATLAB ()
Dynamics Data Exchange (DDE) Word MATLAB
macros - DDE Cells
MATLAB Word
styles text cells
menu Notebook Menu bar Word

 MATLAB Word M-book


prompt MATLAB
notebook

M-book 181
Word template M-book.dot
 document file M-book document
document template M-book New M-book document
file Insert Menu insert file dialog box
file M-book

11.3 Input & Output Cells


MATLAB Word MATLAB
Word cell Word
MATLAB input cell MATLAB
output cell
input cell MATLAB
MATLAB

n Input cell
Input cell cell text cell text
input cell
input cell

MATLAB command window


text
Highlight
Notebook Menu Define Input Cell Alt-D

M-book input cell


input style ( style
) cell mark cell mark [ ]
input cell cell mark
Word cell mark
cell mark

182 M-book
style M-book input cell
Courier New 10 points

input cell
normal text
A=10;
B=20;
C=A*B

highlight input cell


A=10;
B=20;
C=A*B

Notebook Menu Define input cell Alt-D


[A=10;
B=20;
C=A*B]

o input cell
input cell cell MATLAB cell
MATLAB cell

input cell
input cell input cell

Highlight input cell


Notebook Menu Group Cell Alt-G M-book input cell
input cell text
input cell M-book text input cell Group

p AutoInit Cell

M-book 183
input cell file
(Automatic Initialize) AutoInit Cell AutoInit Cell
input cell
input MATLAB
Highlight
Notebook menu Define AutoInit Cell ( short cut key)
M-book AutoInit Cell Cell mark
Courier New 10 points

q MATLAB
input cell MATLAB input cell
AutoInit Cell M-book
input cell M-book MATLAB
input cell cursor cell Notebook
Menu Evaluate Cell Ctrl-Enter
input cell M-book Notebook Menu Evaluate M-book
Alt-R Notebook M-book
input cell M-book highlight input cell ( text
text MATLAB) Notebook
Menu Evaluate cell Ctrl-Enter M-book input cell
cell

r
Notebook output cell output cell ,
Command Window MATLAB Output cell
M-book input cell output text input cell output cell
input cell text input cell
Output cell Command Windows
, Echo,
input cell output cell

184 M-book
output cell Notebook output cell
input cell output cell Notebook output
cell output cell
input cell input cell output 1 Notebook
output cell output output
input cell
output Courier New 10 points


Notebook Menu option
input cell output cell text highlight cell
Notebook Menu Undefined cell Alt-U
output cell Highlight output cell Notebook Menu Purge
Output Cell Alt-P

s Input Output Cell


M-book 1 file
MATLAB MATLAB copy M-book
M-book
M-book file
Clear input
cell M-book M-book
M-book output
input cell output
input cell cell input cell cell
input cell
input cell
Evaluate M-book Alt-R Update

error input cell cell MATLAB
input cell Notebook Menu Options
Options Window Check box Stop evaluating on error Check box

M-book 185
MATLAB error input cell cell
error MATLAB input cell input cell

t Graphic Output
Graphic output output cell
Graphic window M-book Notebook Menu option
Options window cheek box Embed Figures in M-book box
output cell M-book graphic
window command window
Toggle Graph Output for Cell Notebook Menu
Graphic Output cell M-book
Output cell ( Embed Figures in M-book)
input cell cursor cell Toggle Graph output
for cell Notebook Menu cell mark

Word
Graphic Output
Option Notebook Menu
Mouse click picture holder
mouse
MATLAB M-book
click picture holder
shift drag holder
holder
16 256
option Notebook Menu

u Calculate Zone
calculate zone calc zone text, input cell, output cell
M-book calc zone M-book calc zone section
brake brake section calc zone
input output M-book calc zone highlight

186 M-book
, input, output zone Notebook Menu
Define calc zone MATLAB section calc zone input cell

input cell zone Evaluate calc zone
Notebook Menu
calc zone calc zone
zone M-book

11.4 Notebook Menu


M-book Template program MATLAB
() background Menu bar Word
Menu 1 Menu Notebook Menu Menu

Short cut Key


1 Define input cell Alt +D input cell highlight text
MATLAB
2 Define AutoInit cell - Automatic Initialized cell input cell
M-book
Text 1
3 Define Calc Zone - zone zone
4 Undefined Cells Alt + U input output cell text
cell
5 Purge output cell Alt + p output cell cell
6 Group Cell Alt + G Input cell Cell cell
7 Ungroup cell - Group cell 6
8 Hide Cell Marks Alt + [ Cell Mark [...]
(Show Cell Marks) M-book Hide show
Cell Mark
Note Cell Mark
9 Toggle Graph - M-book
Output to Cell Cursor input cell
10 Evaluate Cell Ctrl - Enter input cell highlight input cell
cell cursor cell

11 Evaluate Calc zone Atl - Enter calculate zone calc zone

M-book 187
Short cut Key
12 Evaluate M-book Alt - R M-book input cell
13 Evaluate loop Alt - L M-book loop Cell
Cell
loop
14 Bring MATLAB to Alt - M MATLAB window foreground MATLAB
Front command window background
15 Notebook Options.. - option
1. Number format
format MATLAB
2.
2.1 M-bookEmbed Figures in M-
book
2.2 2.1 16 256

3. M-book Input cell
Stop Evaluation on Error

11.5 M-book Template


M-book Template MATLAB

Style Font
Normal Times New Roman 10 points
AutoInit Courier New 10 points
Error Courier New 10 points
Input Courier New 10 points
Output Courier New 10 points

word Thai
Edition style

1. Format Menu Style

188 M-book
2. Style Window
3. window (style)
4. style highlight style
5. Click Modify Menu bar
6. Fonts...
7. Fonts window ,

8. Click OK Fonts style window
9. style
10. click Apply

Word

M-book 189
12 Handle Graphic

MATLAB


(Low Level Command)
(Graphical User Interface,
GUI) MATLAB

MATLAB


MATLAB
MATLAB
Figure window MATLAB Axes

Figure window axes

Parent & Child Object Hierarchy object
MATLAB

Handle Handle

Handle

Handle

handle

190 Handle Graphic


12.1 MATLAB Graphic Object
MATLAB

handle
object MATLAB object
MATLAB

Object
Root object Root object MATLAB


Figure object MATLAB
Axes object

Image object
Light object. Patches Surfaces
Line object
patch object
Rectangle

Surface object
text object
uicontextmenu object Context menu

uicontrol object MATLAB GUI

uimenu object Menu bar Figure window.

object MATLAB

Handle Graphic 191



Object MATLAB

Root

Figure

Uimenu Uicontextmenu Axes Uicontrol

Image Light Line Patch Rectangle Surface Text

Line Child Axes Line


Axes plot
Parent object Figure Axes Figure
Parent


MATLAB
Handle MATLAB Handle

192 Handle Graphic


(Handle)
MATLAB Object Object
Handle Object
Object Handle


(Property)

12.2 Create Object Function


Root object

Handle
MATLAB

Function Object Description


figure Figure object
axes Axes object
uicontrol Uicontrol object
uimenu Uimenu object
uicontextmenu Uicontextmenu object
image Image object
light Light object
line Line object
patch Patch object
rectangle Rectangle object
surface Surface object
text Text object


MATLAB (Default Value)
Error

Handle Graphic 193



h = function('property name', property value,...)

MATLAB ( line, axes )


'property name' property value
MATLAB Handle h

Read only Property Name
Tag, Visibility ''
Property Value
Handle
Handle h
Handle
Handle


GUI GUI environment



High-Level Low-Level
MATLAB High-level graphics routines plot surf
Low-level graphics routines
High-level graphics routines
High-level routines
high-level graphics routines

High-level graphics routines
Low-level graphics routines


high-level graphics routines plot MATLAB

194 Handle Graphic


plot high-level graphics routines
NextPlot axes figure
replace
object creation functions low-level graphics routines
parent NextPlot
line
Line('XData',x,'YData',y,'ZData',z,'Color','r')

MATLAB axes
x Xdata x y z
axes MATLAB axes
figure window axes MATLAB figure window
MATLAB


high-level functions plot plot graphics objects
axes ( Position Units)
low-level line
high-level functions
hold NextPlot

NextPlot Figure Axes

12.3 Basic Graphic Object Properties



parent
children

Handle Graphic 195


axes object
line object

GUI

MATLAB root
properties handle pointer cursor
figure properties children
axes properties child
parent
child child
parent





GUI


read only



(Default Values)


BusyAction MATLAB callback (
object )

196 Handle Graphic



ButtonDownFcn
Children Handles object children object
Clipping children
axes
CreateFcn
DeleteFcn

HandleVisibility handle

Interruptible

Parent Parent
Selected
SelectionHighlight
Tag
Type object figure, line, text

UserData
Visible


MATLAB
LineStyle XMinorTickMode
MATLAB

2 3

M-files
MATLAB version
2 3

Handle Graphic 197


12.4 GET and SET Function

GET SET

GET
Graphic object
get(object_handle)

returned_value = get(object_handle,'PropertyName');

object_handle handle 'PropertyName'




"

set get

sine

x=linspace(0,2*pi);
y=sin(x);
line_handle = plot(x,y);

198 Handle Graphic


1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

line_handle handle object 2 object


MATLAB handle

gcf (Get Current Figure) MATLAB handle



gca (Get Current Axes) MATLAB handle






handle

handle
fig_handle = gcf

fig_handle =
1

axes_handle = gca

axes_handle =
73.0007

Handle Graphic 199


MATLAB handle 1
handle 73.007
handle (Figure, Axes, Line)
get
Figure MATLAB

get(fig_handle)

BackingStore = on
CloseRequestFcn = closereq
Color = [0.8 0.8 0.8]
Colormap = [(64 by 3) double array]
CurrentAxes = [73.0007]
CurrentCharacter =



WindowButtonUpFcn =
WindowStyle = normal

ButtonDownFcn =
Children = [73.0007]



Tag =
Type = figure
UIContextMenu = []
UserData = []
Visible = on

get(line_handle)

Color = [0 0 1]
EraseMode = normal
LineStyle = -
LineWidth = [0.5]
Marker = none
MarkerSize = [6]
MarkerEdgeColor = auto
MarkerFaceColor = none
XData = [ (1 by 200) double array]
YData = [ (1 by 200) double array]
ZData = []
ButtonDownFcn =
Children = []
Clipping = on

20 Handle Graphic
0
CreateFcn =
DeleteFcn =
BusyAction = queue
HandleVisibility = on
HitTest = on
Interruptible = on
Parent = [73.0007]
Selected = off
SelectionHighlight = on
Tag =
Type = line
UIContextMenu = []
UserData = []
Visible = on


get

l_color=get(line_handle,'Color')

l_color =
0 0 1

l_color
[0 0 1] RGB

n Querying Individual Properties


structure
get(gca,'ColorOrder')
ans =
0 0 1.0000
0 0.5000 0
1.0000 0 0
0 0.7500 0.7500
0.7500 0 0.7500
0.7500 0.7500 0
0.2500 0.2500 0.2500

Structure
output get MATLAB
structure array field field field

a = get(line_handle);

Handle Graphic 201


a structure array field
filed
a.Color
ans =
0 0 1

o Querying Groups of Properties


cell array

camera mode cell array
camera_props(1)={'CameraPositionMode'};
camera_props(2)= {'CameraTargetMode'};
camera_props(3)= {'CameraUpVectorMode'};
camera_props(4)= {'CameraViewAngleMode'};

cell array
get(gca,camera_props)
ans =
'auto' 'auto' 'auto' 'auto'

9 set
set
set
set(object_handle,'PropertyName','NewPropertyValue')

object_handle handle
PropertyName
NewPropertyValue

NewPropertyValue

20 Handle Graphic
2

RGB
[1 0 0]
set(line_handle,'Color',[1 0 0])


quote string
MATLAB
set

set(object_handle,'PropertyName')

MATLAB


MATLAB
set(line_handle,'LineStyle')
[ {-} | -- | : | -. | none ]

[ {-} | -- | : | -. | none ] { }

set(line_handle,'LineWidth')
A line's "LineWidth" property does not have a fixed set of property values.





Set(object_handle)

set(axes_handle)
AmbientLightColor
Box: [ on | {off} ]

Handle Graphic 203


CameraPosition
CameraPositionMode: [ {auto} | manual ]
CameraTarget
CameraTargetMode: [ {auto} | manual ]
CameraUpVector
CameraUpVectorMode: [ {auto} | manual ]


Tag
UIContextMenu
UserData
Visible: [ {on} | off ]

set
structure arrays cell arrays

view1.CameraViewAngleMode = 'manual';
view1.DataAspectRatio = [1 1 1];
view1.ProjectionType = 'Perspective';

set(gca,view1)

output set MATLAB


structure array
a = set(gca);

field a field

a.GridLineStyle

ans =
'-'
'--'
':'
'-.'
'none'

grid line styles

case sensitive
structure field case sensitive

20 Handle Graphic
4
a.gridlinestyle
??? Reference to non-existent field 'gridlinestyle'.

error MATLAB case


sensitive

MATLAB
MATLAB MATLAB
get factory-defined

a = get(0,'Factory');

0 handle root structure array


field field factory
value field
UimenuSelectionHighlight: 'on'

SelectionHighlight uimenu on

Get(0,'FactoryObjectTypePropertyName')


get(0,'FactoryTextFontName')

Windows
ans =
Helvetica

Helvetica

12.5 Related Object Function



GUI

findobj

h = findobj

Handle Graphic 205


h = findobj('PropertyName',PropertyValue,...)
h = findobj(objhandles,...)
h = findobj(objhandles,'flat','PropertyName',PropertyValue,...)

findobj handles


h = findobj

handles root object


findobj
ans =
0
1.0000
73.0007
1.0010

handle root, figure, axes line


h = findobj('PropertyName', PropertyValue,...)

handle PropertyName
PropertyValue
findobj handle

h = findobj(objhandles,...)

handles
h = findobj(objhandles,'flat','PropertyName',PropertyValue,...)

findobj error handle

findobj('Color','r')

20 Handle Graphic
6
Color property red r [1 0 0]

MATLAB findobj
handle

copyobj

new_handle = copyobj(h, p)

copyobj
Parent handle parent
line
axes
new_handle = copyobj(h, p)

handle h handle
children handle p h p
new_handle
new_handle(i) h(i) ] parent
p(i) h p h parents
p new_handle(i) h parent p(i) length(new_handle)
length(p).
h p new_handle(i) h(i)
Parent p new_handle length(h)

surface figure
surface
h = surf(peaks);
colormap hot

figure % figure windows


axes % figure

Handle Graphic 207



new_handle = copyobj(h,gca);
colormap hot
view(3)
grid on


surface colormap figure view grid
axes surface

gca
handle axes ( gca = Get Current Axes)
h = gca

h = gca handle axes figure


MATLAB handle

get(gcf,'CurrentAxes')

MATLAB
current axes MATLAB
plot, text, surf
current axes current figure current axes

gcbo
handle callback
h = gcbo
[h, figure] = gcbo

h = gcbo handle callback [h, figure] =


gcbo handle callback handle figure

MATLAB handle callback root


CallbackObject callback callback MATLAB

20 Handle Graphic
8
CallbackObject handle callback callback
MATLAB handle
CallbackObject root read-only
callback
CurrentFigure root CurrentAxes CurrentObject
callback
callback callback
callback
callback CreateFcn DeleteFcn ResizeFcn
figure gcbo callbacks
CurrentFigure root CurrentObject CurrentAxes figure
CallbackObject root
callbacks gcbo [ ]
gcf
handle (gcf=Get current figure )
h = gcf

h = gcf handle current figure


figure window plot, title surf
MATLAB handle
handle
get(0,'CurrentFigure')

gco
handle current object (gco = get current object)
h = gco
h = gco(figure_handle)

h = gco handle current object h = gco(figure_handle)


current object figure figure_handle.

Handle Graphic 209


current object
uimenus
current object
MATLAB handle the current object CurrentObject figure
CurrentObject CurrentFigure callback
callback callback
CurrentObject CurrentFigure callbacks CreateFcn, DeleteFcn uimenu
Callback CurrentFigure CurrentObject
handle gcbo
handle callback
callback
handle current object figure window 2
h = gco(2)

h =
146.0001

handle
handle

210 Handle Graphic


13 Object Property
(Graphical Object)




GUI
MATLAB



1. Figure Object
2. Axes Object
3. Uicontrol Object
4. Uimenu Object
5. UiContextMenu Object

2 Children Figure Object


object children axes

get set
GUI


MATLAB Reference Book I Reference
Book II Using Graphic Manual
GUI MATLAB

Object Property 211


13.1 Figure
figure graphics object
figure
figure('PropertyName',PropertyValue,...)
figure(h)
h = figure(...)

figure (figure graphics objects) figure objects


MATLAB


figure('PropertyName', PropertyValue,...)

MATLAB


figure(h)

handle h h handle
handle h h
MATLAB handle h
handle h h error
handle
MATLAB handle

h = figure(...) returns the handle to the figure object

MATLAB


structure arrays cell arrays get set gcf
handle

212 Object Property


root
ScreenSize 4 [, , ,
]:
scrsz = get(0,'ScreenSize')
scrsz =
1 1 1024 768

figure('Position',[1 scrsz(4)/2 scrsz(3)/2 scrsz(4)/2])

set(0,'DefaultFigureProperty',PropertyValue...)

Property PropertyValue
set get

Property Name Property Description Property Value

(Positioning the Figure)


Position :
[left, bottom, width, height]
:
Units : inches, centimeters,
normalized, points, pixels,
characters
: pixels
(Specifying Style and Appearance)
Color : ColorSpec
: color
scheme
MenuBar : none, figure
: figure
Name : string
: ' ' (string )
NumberTitle : on, off

Object Property 213


Property Name Property Description Property Value

Figure No. n, n : on

Resize : on, off
: on
SelectionHighlight : on, off
: on
Visible : on, off
: on
WindowStyle : normal, modal
: normal
(Controlling the Colormap)
Colormap colormap : m x 3
RGB
: jet colormap
Dithermap Colormap truecolor : m x 3
data RGB
pseudocolor : colormap

DithermapMode MATLABdithermap : auto, manual
: manual
FixedColors colormap : m x 3
RGB read only
MinColormap : scalar
: 64
ShareColors MATLAB color table on, off
slots : on
(Specifying the Renderer)
BackingStore off screen pixel buffering : on, off
: on
DoubleBuffer : on, off
: off
Renderer : painters, zbuffer,
OpenGL
:
MATLAB

214 Object Property


Property Name Property Description Property Value

(General Information About the Figure)


Children Handle uicontrol, uimenu : handles
uicontextmenu
Parent root object Value: always 0
parent

Selected : on, off
: on
Tag : string
: string
Type (read only) : string 'figure'
UserData :
: [ ] ()
RendererMode : auto, manual
: auto
(Information About Current State)
CurrentAxes Handle : handle axes

CurrentCharacter : character (read only)



CurrentObject Handle : graphics object handle

CurrentPoint : 2-element
[x-coord, y-coord]

SelectionType (read only) : normal, extended,


alt, open
Callback Routine Execution
BusyAction : cancel, queue
: queue

ButtonDownFcn : string
: string

CloseRequestFcn : string
close : string

Object Property 215


Property Name Property Description Property Value


CreateFcn : string
: string
DeleteFcn : string
: string
Interruptible : on, off
: on ()
KeyPressFcn : string
: string
ResizeFcn : string
: string
UIContextMenu context menu : handle Uicontrextmenu
WindowButtonDownFcn : string
: string
WindowButtonMotionFcn : string
: string
WindowButtonUpFcn : string
: string
(Controlling Access to Objects)
IntegerHandle handle : on, off
: on (handle
)
HandleVisibility handle : on, callback, off
: on
HitTest : on, off
( : on
CurrentObject )
NextPlot : add, replace,
replacechildren
: add
(Defining the Pointer)
Pointer : crosshair, arrow,
watch, topl, topr, botl, botr,
circle, cross, fleur, left,
right, top, bottom,

216 Object Property


Property Name Property Description Property Value

fullcrosshair, ibeam,
custom
: arrow
PointerShapeCData : 16-by-16 matrix
: Pointer
custom
PointerShapeHotSpot active spot : 2-element
[row, column]
: [1,1]
(Properties That Affect Printing)
InvertHardcopy : on, off
: on
PaperOrientation : portrait, landscape
: portrait
PaperPosition : 4-element
[left, bottom, width, height]

PaperPositionMode WYSIWYG : auto, manual


: manual

PaperSize : [width, height]


PaperUnits

PaperType
read only
PaperType : see property
description
: usletter
PaperUnits : normalized, inches,
PaperSize centimeters, points
PaperPosition : inches

set get

Object Property 217


13.2 Axes

figure

axes
axes('PropertyName',PropertyValue,...)
axes(h)
h = axes(...)

axes (low-level function)


Figure (current figure)
MATLAB

axes object

Property Name Property Description Property Value

(Controlling Style and Appearance)


Box axes plot box on off : on, off
: off
Clipping axes axes
(clip) figure

GridLineStyle grid : -, --, :, -., none
: :()
Layer : bottom, top
: bottom
LineStyleOrder : LineSpec
: - ()
LineWidth points (1 point = : points
1/72") : 0.5 points
SelectionHighlight axes on : on, off
: on
TickDir (tick marks) : in, out
: in(2-D),out(3-D)
TickDirMode MATLAB : auto, manual

218 Object Property


Property Name Property Description Property Value

: auto
TickLength : [2-D 3-D]
: [0.01 0.025]
two-element vector
Visible : on, off
: on
XGrid, YGrid, ZGrid grid : on, off
: off
(General Information About the Axes)
Children Handles images, lights, lines, patches, : handles
surfaces text
CurrentPoint : 2x3

HitTest current object : on, off
: on
Parent Handle figure : figure
handle
Position figure : [left bottom width
Height]
: [0.1300 0.1100
0.7750 0.8150]

Selected : on, off
: on
Tag : any string
: '' ( string )
Type : string 'axes'

Units : inches, centimeters,
'Position' Characters, normalized,
Points, pixels
: Normalized
UserData : any matrix
: [ ] ()
(Selecting Fonts and Labels)
FontAngle : normal, italic, Oblique

Object Property 219


Property Name Property Description Property Value

: normal
FontName Helvetica :
Courier
: Helvetica
FontSize :

: 10
FontUnits : points, normalized,
FontSize inches, centimeters, pixels
: points
FontWeight : normal, bold, light,
demi
: normal
Title Handle title : handle
title
XLabel, Handles : Handles
YLabel,
ZLabel

XTickLabel, tick mark labels : strings


YtickLabel, :
ZtickLabel MATLAB
XTickLabelMode, MATLAB : auto, manual
YTickLabelMode, tick mark labels : auto
ZtickLabelMode
(Controlling Axis Scaling)
XaxisLocation x : top, bottom
: bottom
YaxisLocation y : right left
: left
XDir, YDir, Zdir : normal, reverse
: normal
XLim, Ylim, Zlim : [min max]
:

MATLAB

220 Object Property


Property Name Property Description Property Value

XlimMode, MATLAB : auto, manual


YlimMode, : auto
ZlimMode
XScale, linear logarithmic : linear, log
YScale, : linear (
Zscale plot
log )
XTick, ticks marks :
YTick, tick
Ztick marks
:
MATLAB
XTickMode, MATLAB : auto, manual
YTickMode, tick mark : auto
ZtickMode
(Controlling the View)
CameraPosition : [x,y,z]

:
MATLAB
CameraPositionMode MATLAB : auto, manual
: auto
CameraTarget : [x,y,z]

:
MATLAB
CameraTargetMode MATLAB : auto, manual
: auto
CameraUpVector : [x, y, z]

:
MATLAB
CameraUpVectorMode MATLAB : auto, manual
: auto

CameraViewAngle : 0180

Object Property 221


Property Name Property Description Property Value

:
MATLAB
CameraViewAngleMode MATLAB : auto, manual
: auto
Projection projection : orthographic,
perspective
: orthographic
(Controlling the Axes Aspect Ratio
DataAspectRatio :
[dx dy dz]
:
MATLAB
DataAspectRatioMode MATLAB : auto, manual
: auto
PlotBoxAspectRatio :
[dx dy dz]
:
MATLAB
PlotBoxAspectRatioMode MATLAB : auto, manual
: auto
Callback (Controlling Callback Routine Execution)
BusyAction : cancel, queue
: queue
ButtonDownFcn : string
: string
CreateFcn : string
: string
DeleteFcn : string
: String
Interruptible : on, off
: on
UIContextMenu contextmenu : handle
Uicontextmenu
(Specifying the Rendering Mode)
DrawMode (rendering) : normal, fast
: normal

222 Object Property


Property Name Property Description Property Value

(Targeting Axes for Graphics Display)


HandleVisibility : on, callback, off
: on

NextPlot : add, replace,


replacechildren
: replace
(Properties that Specify Color)
AmbientLightColor : ColorSpec
: [1 1 1]
CLim Colormap : [cmin cmax]
: MATLAB

CLimMode MATLAB Clim : auto, manual
: auto
Color : none, ColorSpec
: none
ColorOrder : m x 3
RGB
:

XColor, tick marks : ColorSpec
YColor, :
ZColor

1.


M-file

Object Property 223


h(1)= axes('Position',[0 0 1 1]);
sphere
shading interp
h(2)= axes('Position',[0 0 .4 .6]);
sphere

h(3)= axes('Position',[0 .5 .5 .5]);


sphere
shading interp

h(4)=axes('Position',[5 0 .4 .4]);
sphere

h(5)= axes('Position',[.5 .5 .5 .3]);


sphere
colormap(hot)
shading interp
set(h,'Visible','off')

m-file

2. X Y

Y
X X

224 Object Property


MATLAB 5.0 plotyy

Y x
XAxisLocation YAxisLocation X
Y 2
XaxisLocation and YAxisLocation
X Y

2
x-y

low-level line axes


Handle
x1 x2

x1=linspace(0,30);
y1=sin(x1).^exp(-x1/10);
hl1= line(x1,y1,'color','r');
ax1= gca;
set(ax1,'Xcolor','r','Ycolor','r');
grid on



x y none

ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k','YColor','k');

Object Property 225


x2=x1/10;
y2=100*sin(x2/30).*exp(-x2);
hl2 = line(x2,y2,'Color','k','Parent',ax2);
grid on

0 0.5 1 1.5 2 2.5 3


1 1.4

0.8
1.2

0.6
1
0.4

0.2 0.8

0 0.6

-0.2
0.4
-0.4

0.2
-0.6

-0.8 0
0 5 10 15 20 25 30

grid grid on
grid
grid
grid grid grid

grid tick mark


tick mark grid
tick mark
tick mark
tick mark
tick mark tick mark 7 x (
) y tick mark 8
tick mark

226 Object Property


xlimits = get(ax1,'XLim');
ylimits = get(ax1,'YLim');

x y
xinc = (xlimits(2)-xlimits(1))/6;
yinc = (ylimits(2)-ylimits(1))/7;
tick mark
set(ax1,'XTick',[xlimits(1):xinc:xlimits(2)],...
'YTick',[ylimits(1):yinc:ylimits(2)])

0 0.5 1 1.5 2 2.5 3


1 1.4

0.7429 1.2

0.4857 1

0.2286 0.8

-0.0286 0.6

-0.2857 0.4

-0.5429 0.2

-0.8 0
0 5 10 15 20 25 30

trick mark y
limit y 7 y 8 trick mark
7 1 1.1
2.1 7 0.3
ylimits = [-1.0 1.1];
set(ax1,'YLim',ylimits);
yinc = (ylimits(2)-ylimits(1))/7;
set(ax1,'XTick',[xlimits(1):xinc:xlimits(2)],...
'YTick',[ylimits(1):yinc:ylimits(2)])

Object Property 227



0 0.5 1 1.5 2 2.5 3
1.1 1.4

0.8 1.2

0.5 1

0.2 0.8

-0.1 0.6

-0.4 0.4

-0.7 0.2

-1 0
0 5 10 15 20 25 30

228 Object Property


X2 value
0 0.5 1 1.5 2 2.5 3
1.1 1.4

0.8 1.2

0.5 1

0.2 0.8
Y1 value

Y2 value
-0.1 0.6

-0.4 0.4

-0.7 0.2

-1 0
0 5 10 15 20 25 30
X1 value

13.3 Uicontrol
user interface control object
handle = uicontrol(parent)
handle = uicontrol(...,'PropertyName',PropertyValue,...)

uicontrol uicontrol (user interface controls)


GUI uicontrols uicontrol
MATLAB
uicontrol
uicontrol MATLAB

1. Check boxes
2. Editable text
3. Frames
4. List boxes
5. Pop-up menus
6. Push buttons

Object Property 229


7. Radio buttons
8. Sliders
9. Static text
10. Toggle buttons



GUI

uicontrol

uicontrol

1. Check boxes

check box

2. Editable text boxes

230 Object Property


fields
editable text input
Microsoft Windows editable text box focus menu bar callback
editable text UNIX
Microsoft Windows editable text box menu bar
get(edit_handle,'String') MATLAB
edit box MATLAB callback
String

3. Frames
Frames

uicontrol
uicontrol Frames callback
uicontrols frames Frames
frame uicontrols
uicontrols frame frame
Stacking order uicontrols

frame frame

4. List boxes
String

Min Max Value

Value MATLAB
callback list box
Value

Object Property 231


Done GUI callback
List boxes
(double clicks)
SelectionType figure normal open
callback

5. Pop-up menus

String
Pop-up menus

String

6. Push buttons

Push buttons
7. Radio buttons
check boxes
Radio button Radio button
radio button

8. Sliders

slider


slider

9. Static text boxes



232 Object Property



GUI
static text interactive callback static text

10. Toggle buttons


on off
callback
Toggle buttons toolbars

uicontrol structures
cell arrays arguments handle
set get
Uicontrol children figures axes

uicontrol objects

Property Name Property Description Property Value


Controlling Style and Appearance
BackgroundColor background : ColorSpec
:
Cdata Truecolor image control : matrix
FegroundColoror : ColorSpec
: [0 0 0]
SelectionHighlight : on, off
: on
String Uicontrol : string
list
box pop-up menu
Visible : on, off
Uicontrol : on
General Information About the Object

Object Property 233


Property Name Property Description Property Value
Children Uicontrol objects
children
Enable uicontrol : on, inactive, off
(Enable disable) : on
Parent parent Uicontrol : scalar figure handle
Selected : on, off
: off
SliderStep slider : two-element vector
: [0.01 0.1]
Style uicontrol object : pushbutton,
togglebutton,
radiobutton, checkbox,
edit, text, slider, frame,
listbox, popupmenu
: pushbutton
Tag : string
TooltipString tooltip : string
object
Type graphics object : string (read-only)
: uicontrol
UserData User-specified data ( : matrix
) : [ ]
Controlling the Object Position
Position : position rectangle
uicontrol : [20 20 60 20]
Units : pixels, normalized,
inches, centimeters,
points, characters
: pixels
Controlling Fonts and Labels
FontAngle : normal, italic,
oblique
: normal
FontName Font family () : string
:
FontSize : size in FontUnits

234 Object Property


Property Name Property Description Property Value
:
FontUnits : points, normalized,
inches, centimeters,
pixels
: points
FontWeight : light, normal, demi,
bold
: normal
HorizontalAlignment : left, center, right
VerticalAlignment : uicontrol object
String Uicontrol : string
list
box pop-up menu
Controlling Callback Routine Execution
BusyAction Callback : cancel, queue
: queue
ButtonDownFcn callback : string

Callback : string

CreateFcn Callback : string

DeleteFcn Callback : string

Interruptible Mode : on, off
Callback : on
UIContextMenu Uicontextmenu : handle
Information About the Current State
ListboxTop : scalar
List box : [1]
Max : scalar
uicontrol :
Min : scalar
uicontrol :
Value uicontrol : scalar or vector
:
Controlling Access to Objects

Object Property 235


Property Name Property Description Property Value
HandleVisibility handle : on, callback, off
command line : on
GUIs
HitTest : on, off
: on

push button
h = uicontrol('Style', 'pushbutton', 'String', 'Clear',...
'Position', [20 150 100 70], 'Callback', 'cla');

uicontrol colormaps figure pop-up


menu M-file Callback
hpop = uicontrol('Style', 'popup',...
'String', 'hsv|hot|cool|gray',...
'Position', [20 320 100 50],...
'Callback', 'setmap');

uicontrol
hsv, hot, cool gray String
|
Callback M-file setmap
M-file callback

M-file callback setmap
M-file M-file setmap

val = get(hpop,'Value');
if val ==1
colormap(hsv)
elseif val ==2
colormap(hot)
elseif val ==3
colormap(cool)
elseif val ==4
colormap(gray)
end

236 Object Property


Value 1 4 hsv
value 1
uicontrol command line
GUI
command line

13.4 Uimenu

uimenu('PropertyName', PropertyValue,...)
uimenu(parent, 'PropertyName', PropertyValue,...)
handle = uimenu('PropertyName', PropertyValue,...)
handle = uimenu(parent,'PropertyName',PropertyValue,...)

uimenu
uimenu context menu
Handle = uimenu('PropertyName',PropertyValue,...)

handle

handle = uimenu(parent,'PropertyName',PropertyValue,...)

(submenu) handle parent


parent handle figure uimenu object Uicontextmenu MATLAB

MATLAB

uimenu
property name property value structures cell arrays
input arguments Callback uimenu
MATLAB Uimenus
WindowStyle normal figure object
uimenu WindowStyle modal

Object Property 237


MenuBar figure
MenuBar figure
MATLAB
MenuBar none

uimenu

Property Name Property Description Property Value


Controlling Style and Appearance
Checked : on, off
: off
ForegroundColor : ColorSpec
: [0 0 0]
Label Menu : string
SelectionHighlight : on, off
: on
Separator Separator line : on, off
mode : off
Visible Uimenu : on, off
: on
General Information About the Object
Accelerator Keyboard equivalent : character
Children Handles : vector of handles
Enable uimenu : on, off
: on
Parent handle parent : handle
Uimenu
Tag : string
Type graphics object : string (read-only)
: uimenu
UserData : matrix
Controlling the Object Position
Position uimenu : scalar
: [1]
Controlling Callback Routine Execution

238 Object Property


Property Name Property Description Property Value
BusyAction Callback : cancel, queue
: queue
ButtonDownFcn callback : string

Callback : string

CreateFcn Callback : string

DeleteFcn Callback : string

Interruptible Callback : on, off
: on
Controlling Access to Objects
HandleVisibility handle : on, callback, off
: on
command line
GUIs
HitTest : on, off
: on


Workspace figure window
(save) workspace MATLAB
Ctrl Q Quit
accelerator key
f = uimenu('Label','Workspace');
uimenu (f,'Label','New Figure','Callback','figure');
uimenu (f,'Label','Save','Callback','save');
uimenu (f,'Label','Quit','Callback','exit',...
'Separator','on','Accelerator','Q');

Object Property 239


13.5 Uicontextmenu
context menu
handle = uicontextmenu('PropertyName',PropertyValue,...);

uicontextmenu context menu


context menu uimenu

UIContextMenu handle context menu UIContextMenu
uicontextmenu objects

Property Name Property Description Property Value


Controlling Style and Appearance
Visible Uicontextmenu : on, off
: off
Position uicontextmenu : two-element vector
Visible on : [0 0]
General Information About the Object
Children handle uimenus : matrix
uicontextmenu
Parent parent Uicontextmenu : scalar figure handle
Tag : string
Type graphics object : string (read-only)
: uicontrol
UserData : matrix
Controlling Callback Routine Execution
BusyAction Callback : cancel, queue
: queue

240 Object Property


Property Name Property Description Property Value
Callback : string

CreateFcn Callback : string

DeleteFcn Callback : string

Interruptible Callback : on, off
: on
Controlling Access to Objects
HandleVisibility handle : on, callback, off
: on
command line
GUIs


context menu line

M-file
% context menu
cmenu = uicontextmenu;
% context menu
hline = plot(1:10,'UIContextMenu',cmenu);
% callbacks context menu
% 3
cb1 = ['set(hline, ''LineStyle'', ''--'')'];
cb2 = ['set(hline, ''LineStyle'', '':'')'];
cb3 = ['set(hline, ''LineStyle'', ''-'')'];
% context menu
item1 = uimenu(cmenu, 'Label', 'dashed', 'Callback', cb1);
item2 = uimenu(cmenu, 'Label', 'dotted', 'Callback', cb2);
item3 = uimenu(cmenu, 'Label', 'solid', 'Callback', cb3);

M-file

Object Property 241


context menu MATLAB
line object context menu GUI

children Axes




MATLAB

242 Object Property


14 GUIDE
Graphical User Interface (GUI) user interface graphical object
slider objects object
slider

Application GUI application
application
input
GUIDE
GUI GUIDE
GUIDE
GUIDE GUI
GUIDE

14.1 GUI GUIDE


MATLAB GUI (figure window)
axes, uicontrol
MATLAB version uicontrol , uimenu
text base version5
MATLAB Graphical User Interface Development Environment GUIDE
GUI
GUI
GUI
GUI
GUIDE GUI
GUIDE M-file handle object

Introduction to GUIDE 243


GUI M-file
callback

14.2 GUI MATLAB


GUI M-file
GUIDE
GUIDE 2 GUI

FIG-file
GUI
M-file GUI callback
callback sub function M-file M-file
GUI Application M-file
Application M-file
GUI FIG-file

n Application M-file GUIDE


GUIDE GUI Application M-file
Application M-file
GUI

M-file GUI
M-file
M-file MATLAB
Application M-file Sub function uicontrols GUI
callback

GUIDE GUIDE fig-file


GUI M-file GUI
MATLAB GUI GUIDE GUIDE Application M-file
GUI GUIDE
GUIDE Application option GUIDE FIG-file M-file

244 Introduction to GUIDE


Layout Editor GUI
Application M-file GUIDE
Application M-file

Note GUIDE Application M-file Fig-file Layout Editor


GUI Active Layout Editor, GUIDE Application M-file
GUI

o GUIDE Application Options


GUIDE MATLAB COMMAND WONDOW prompt
guide

Layout Editor

GUI
Tool Application Options

Introduction to GUIDE 245


GUIDE Application Options

GUIDE FIG-file Fig-file M-file


Resize Behavior

GUI
MATLAB GUIDE 3

Non-Resizable (default)
Proportional GUI MATLAB
GUI GUI
User-Specifide GUI
GUI GUI
GUI

GUI
Proportional
Proportional
GUI
User-Specify

246 Introduction to GUIDE


Command-Line Accessibility

MATLAB graph figure axes parents MATLAB


figure Axes MATLAB
figure Axes MATLAB figure Axes

GUI axes
GUI axes
GUI GUIDE Command-Line Accessibility

Off - command-line GUI (default)


On command-line GUI
User-Specified GUIDE GUI Handle Visibility
Integer Handle figure

Note Findobj GUI Handle Visibility Figure off


handle figure MATLAB figure
Application M-file handle GUI
findobj handle figure
figure 2

Handle Visibility off handle children


figure children root object figure current figure
(current figure MATLAB) handle
handle
Integer Handle off MATLAB handle
(68.0001224)
GUI handle
GUI

Introduction to GUIDE 247


14.3 Application M-file GUIDE
GUI GUIDE GUIDE FIG-file M-file
4 Application M-file

Generate callback function prototypes
Application allows only one instance to run
Use system color scheme for background
Function does not return until application window dismissed

n Application M-file
Generate Callback Function Prototype GUIDE Application
Option GUIDE sub function application M-file GUI
( frame Static text) GUEDE sub function
sub function GUIDE sub
function callback context
callback sub function

function object.Tag_Callback(h,eventdata,handles.varagin)

arguments
h handle callback
eventdata
handles structure handle GUI
file tag handle
GUI callback
MATLAB
varargin variable-length callback function
push button Tag pushbutton1
GUIDE sub function application

function pushbutton1_Callback(h,evendata,handles,varargin)

248 Introduction to GUIDE


GUIDE Callback push button

Mygui(pushbutton1_callback,gcbo,[],guidata(gcbo))

Mygui FIG-file GUI


Pushbutton1 Callback- callback sub funcion
gcbo handle push button
[ ] eventdata
guidata(gcbo) handles structure figure GUI

sub function GUIDE


argument
, (1) sub function application M-file (2)
callback gx1 gx2 subfunction
function M-file

MYGUI(pushbutton1_callback,gcbo,[],guidata(gcbo),gx1,gx2)

GUI
GUI
MATLAB GUI
MATLAB GUI

MATLAB GUI MATLAB


GUI GUI
MATLAB GUI GUI
code application M-file application M-file

fig = openfig(mfilename,reuse)

fig = openfig(mfilename,new)

Note openfig application M-file command line

Introduction to GUIDE 249


o System MATLAB
GUI
uicontrol figure GUI
uicontrol

application M-file

%Use system color scheme for figure


set(fig,color,get(0,Default UIcontrol Background Color);

Note M-file command line

p input
GUIDE application option

Function does not return until application window dismissed

application M-file input


uiwait M-file

MATLAB

GUI
GUI callback uiresume

MATLAB command line


dialog box callback
application M-file code
%wait for callbacks to run and window to be dismissed
uiwait(fig);

fig handle figure

Note M-file command line

250 Introduction to GUIDE


q Tag
GUI Tag
GUIDE Tag ()
pushbutton1 string callback sub function
pushbutton1_callback

Tag
active save GUI
save as GUIDE application M-file
callback callbacks
Note GUIDE Tag function structure file Tag
MATLAB
Tag Activate save GUI
Application M-file Tag
application M-file
GUIDE application M-file
application M-file
Tag application M-file GUIDE sub function
handles MATLAB GUIDE Tag
file handles application M-file
x = get(handles,listbox1,string)

Tag Listbox1 graph


x = get(handles,graph,string)

GUI file structure handles listbox1


error MATLAB

FIG-file M-file M-file
GUIDE file extension ( fig M) file file

Introduction to GUIDE 251


GUI Building Tools (GUI Layout Tool)

MATLAB GUI GUI Layout tools


GUI GUI uicontrol
axes GUI

Layout Editor GUI


Alignment Tool GUI
Property Inspector
Object Browser handle MALAB
Menu Editor context menu

GUIDE Layout Editor


Layout Editor
guide

MATLAB GUI GUI

guide mygui.fig

( .fig ) GUI GUI


open File Layout Editor

r GUI Layout Editor


Layout Editor
uicontrol axes

1. uicontrol axes GUI component palette


2. GUI cursor


252 Introduction to GUIDE


3.

s Activating the Figure


GUI activate figure
Layout Editor Activate activate figure Tool Activator
button Toolbar
activate figure
GUIDE SAVE M-file Fig-file file
SAVE Dialog box SAVE AS FILE SAVE
MATLAB (Append)

Note GUI
Tag GUI Activate Figure

Layout Editor Context Menu

Layout Editor
context menu
context menu subfunction application M-file
callback routine
Context figure

Introduction to GUIDE 253


t Aligning Component in The Layout Editor


Alignment Tool Alignment Tool Alignment Tool
Alignment Tool

Alignment Tool
(select) component palette

254 Introduction to GUIDE


Align
Shift


Vertical Horizontal
Apply
Alignment Tool Grids Rulers
grid Grid and Rulers
Layout

Grid size 10 57 200 Pixel 50 default


Snap-to-grid 9 pixels
grid grids snap-to-grid
grid Layout Editor
guide line
guide line ruler
gui
grid grid

Introduction to GUIDE 255


GUI
GUI
context menu

Bring to Front, Send to back, Bring Forward send Backward

14.4
GUI Property
Inspector


Property Inspector

Property Inspector Tools
Inspect property Edit
Inspect Properties context

256 Introduction to GUIDE


Property Inspector Toolbar

Property Inspector Layout Editor


Property

Property Inspector
Mixed


n The Object Browser

Introduction to GUIDE 257


OBJECT BROWSER
figure children figure
object Browser GUI

The Menu Editor

MATLAB
Menu bar object - figure menu bar
Context Menu -

Menu Editor
Menu Editor Layout Editor Toolbar Edit Menu bar Layout Menu Editor

258 Introduction to GUIDE


UI menu UIcontext menu
o Menubar
MATLAB figure Menu bar

New Menu Toolbar

UI MENU Property
Lable (), Tag () Seperator () Checked
Menu property () Callback menu

Introduction to GUIDE 259


New Menu Item
Print File
New
Menu Item New Menu Item

p callback
callback
MATLAB callback Menu Editor
print-dsp Subfunction
Application- M file GUIDE UI control callback

Note GUIDE callback subfunction application M-file


subfunction
callback String
callback
subfunction

My Gui (Name_of_subfunction, gcbo, I J, guidata (gcbo))

My Gui Applicaton M-file

Name_of_subfunction subfuncton

gcbo handle
[]
guidata (gcbo) handles GUI

260 Introduction to GUIDE


callback Menu Editor application M-file
subfunction Name_of_ subfunction

q Context Menu
Context Menu
Menu Editor context menu

1. Paren Menu context menu children context menu


figure paren menu Context Menus tab
Menu Editor New Context menu

2. Tag context menu


3. callback String
4.
5. Context menu Layout Editor
Property Inspector UI context Menu Context
Menu
6. Callback subfunction

Introduction to GUIDE 261


14.5 User Interface Controls
User interface control 1) Check Boxes, 2) Editable Text, 3) Frames 4)
List boxes, 5) Push Buttons, 6) Radio Buttons, 7) Sliders, 8) Static Text, 9) Toggle Buttons
object Properties
GUIDE MATLAB
6.0 Callback subfunction ( frame Static text)
Tag subfunction DUIDE
Control default Tag

UI Control Default Tag


Check Boxes checkbox1, checkbox2,..
Editable Text edittext1, ..
Frames frame1, ..
List Boxes listbox1, .
Push Buttons pushbutton1,
Radio Buttons radiobutton1,
Slider slider1,
Static Text text1,
Toggle Buttons Togglebottom1,

14.6 Understanding the Application M-File


Application M-file GUI
Fig-file GUIDE GUI Application M-file
Code Subfunction Application
M-file Callback Subfunction Callback
Initialize GUI
M-file GUI application M-
file GUIDE
Application M-file GUIDE
M-file
GUI Application M-file

262 Introduction to GUIDE


 Callback
 Application M-file
 Application M-file

n Automatic Naming of Callback Routines


GUIDE Callback subfunction
Layout Editor Static Text Frame GUI
MATLAB Callback Callback subfunction application M-file
MATLAB Subfunction GUIDE GUI
GUIDE

1. GUI GUIDE Layout Editor


2. Save GUI Layout Editor GUIE
 Application M-file Fig-file GUI
 Callback
my_gui('ObjectTag_Callback',gcbo,[],guidata(gcbo))

my_gui application M-file save


ObjectTag_Callback Subfunction Application M-file
ObjectTag Tag
Tag pushbutton1 subfunction pushbutton1_Callback
subfunction application M-file GUI

gcbo get callback object handle Callback

[ ]
guidata(gcbo) handle GUI
GUI
GUI GUIDE Subfunction
ObjectTag_Callback GUI MATLAB
Application M-file ( my_gui.m)
Subfunction ObjectTag_CallBack application M-file Subfuction

Introduction to GUIDE 263


% ---------------------------------------------------------------
function varargout = ObjectTag_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.ObjectTag.
disp('ObjectTag Callback not implemented yet.')

input Subfunction
h handle
eventdata
handles structure field handle
GUI field Tag GUI
3
Figure Tag figure1 handle
1.00256
Push Buttom Tag ObjectTag handle 5.00123
Slider Tag slider1 handle 6.00301

handles Structure 3 field


handles.figure1 1.00256

handles.ObjectTag 5.00123

handles.slider1 6.00301

handle GUI findobj


GUI version MATLAB

varargin (variable argument input)

disp('ObjectTag Callback not implemented yet.')

Command Window
Callback Subfuction

o Application M file

264 Introduction to GUIDE


Application M-file M-file Command
Windows
1. M-file

2. M-file Subfunction

callback

GUIDE Switchyard Code GUI


GUI

The Switchyard Code

GUI
Switchyard Code
GUIDE

if nargin == 0 % LAUNCH GUI

fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));

% Generate a structure of handles to pass to callbacks, and store it.


handles = guihandles(fig);
guidata(fig, handles);

if nargout > 0
varargout{1} = fig;
end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

try
[varargout{1:nargout}]=feval(varargin{:});%FEVAL switchyard
catch
disp(lasterr);
end
end

code

Introduction to GUIDE 265


if nargin == 0 % LAUNCH GUI if
Command line GUI 0
MATLAB GUI GUI

fig = openfig(filename,'reuse'); GUI


FIG-file reuse GUI
( )
GUI new

set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
uicontrol GUI GUI
GUI

handles = guihandles(fig); guihandles structure


field
handles handle fig field
Tag handles

guidata(fig, handles) handles


guidata
MATLAB handles

GUI
handles

if elseif GUI
MATLAB
Subfunction Subfunction

266 Introduction to GUIDE


GUIDE GUI
GUI GUI

14.7 GUI
GUI MATLAB
MATLAB GUIDE
Callback GUI

GUI
GUI
GUI
GUI
GUI
GUI
GUI GUI
GUI GUI
GUI GUI
GUI GUI

GUI
GUI

GUI
GUI
GUI

Introduction to GUIDE 267


GUI
GUI GUI

Interactive
GUI


GUI


Slider

o
GUI


GUI

p

File
help

GUI

GUI

268 Introduction to GUIDE





A simple design is a good design.

14.8 GUI
GUI
GUI GUI
GUI GUI




GUI

GUI


GUI
GUI


callback

Introduction to GUIDE 269



GUI GUI
MATLAB GUIDE
figure windows callback Callback Editor

GUI calback



MATLAB
GUI MATLAB web site

14.9
GUI

Editable text object
String Slider
Slider Value

270 Introduction to GUIDE


15 GUIDE

GUIDE
GUIDE



GUI MATLAB

15.1 Radio Button


GUI GUIDE
application M-file
GUI Radio Button
GUI

Getting Start with GUIDE 271


radio button check box
GUI

GUIDE Layout Editor


GUIDE Command Windows
GUIDE

GUIDE Layout Editor

Allocation Option Tool


MATLAB

uicontrol GUI Radio Button


4 Radio Button Tool Pallet

Radio Button
4

Static Text
GUI

272 Getting Start with GUIDE


Frame GUI Frame
Tool Pallet Radio Button Frame Radio Button
Frame Radio Button
Frame Context Menu
Send to Back Frame Radio Button
GUI Alignment Tool

Tag
Property Inspector
Property Inspector

Getting Start with GUIDE 273


Figure
Layout Editor Property Inspector

Radio Button
Property Inspector Tag String

Tag radiobutton1 String Radio Button default



Tag Option1 String Option 1
String Radio Button Option 1
Tag String Radio Button Option2,
Option3, Option4 Option 2, Option 3, Option 4

274 Getting Start with GUIDE


Value Radio Button Option 1 0.0
1.0 default
Static Text String Default Static Text
You have select Option 1 default

Save Activate GUI


Save GUI
Save File MATLAB
option Click OK MATLAB
option.fig
Application M-file option.m

MATLAB GUI

Editor/Debugger option.m

Getting Start with GUIDE 275


Option GUI Command Windows

Option3 Callback not implemented yet.

callback subfunction option.m

GUI

Radio Button
Option 2 Option 1
subfunction

% ----------------------------------------------------------------
function Turn_Off(off)
set(off,'Value',0);
% ----------------------------------------------------------------

276 Getting Start with GUIDE


Subfunction Turn_Off off off
vector handle value handle
off radio button
subfunction
subfunction callback uicontrol
subfunction Option 1
function varargout=Option1_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Option1.
disp('Option1 Callback not implemented yet.')

disp('...')

off = [handles.Option2 handles.Option3 handles.Option4];


turn_Off(off);
set(h,'Value',1);
set(handles.text1,'String','You have selected Option 1');

off vector handle Radio Button


off function Turn_Off
Value 3 Value (h
handle Callback) 1
( Radio Button
(value = 1) (value = 0) (value = 0)
(value = 1)
String Static Text handles
handles.text1 You have selected Option 1 1
subfunction

% ----------------------------------------------------------------
function varargout=Option2_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Option2.
off =[handles.Option1 handles.Option3 handles.Option4];
Turn_Off(off);
set(h,'Value',1);
set(handles.text1,'String','You have selected Option 2');

% ----------------------------------------------------------------
function varargout=Option3_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Option3.

Getting Start with GUIDE 277


off =[handles.Option1 handles.Option2 handles.Option4];
Turn_Off(off);
set(h,'Value',1);
set(handles.text1,'String','You have selected Option 3');

% ----------------------------------------------------------------
function varargout=Option4_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Option4.
off =[handles.Option1 handles.Option2 handles.Option3];
Turn_Off(off);
set(h,'Value',1);
set(handles.text1,'String','You have selected Option 4');

Subfunction off
Value = 0
GUI Save

GUI
GUI
GUI Command Windows
option

GUI




GUI
GUI title Untitled
GUI
Layout Editor figure Property Inspector
Name Untitled My First GUI: Option ( )
Save Layout Editor
update GUI
update GUI Activate GUI
GUI

278 Getting Start with GUIDE


GUI GUI
GUI GUI
Subfunction Callback Function

Function-file

15.2 Slider Editable Text


uicontrol GUI

Slider Value
Slider

Max Min
Value
Editable Text
String Editable Text
String Numeric

GUI
 Slider Editable Text

slider
 Editable Text Slider


 Slider 10 0

Editable Text

GUIDE Layout Editor

Getting Start with GUIDE 279


GUIDE Command Windows
GUIDE

Layout Editor uicontrol


Editable Text Slider

Tag
Property Inspector
Property Inspector Tag
Editable Text Tag edit1 Slider Tag slider1

Slider
Default 0 1 Max
10 Value Slider 0 default
Editable Text String
0 string
0 a

Save Activate GUI


Save GUI Save File
MATLAB numerical OK
MATLAB numerical.fig numerical.m
Activate GUI MATLAB GUI
Editor/Debugger numerical.m

GUI
Slider Editable Text String
Editable Text Slider
2
 str2num(X) String X X

[ ]

280 Getting Start with GUIDE


 num2str(X) X String

Slider callback slider1_Callback


nvalue = get(h,'Value');
svalue = num2str(nvalue);
set(handles.edit1,'String',svalue);
Value
nvalue nvalue String
String Editable Text Tag edit1 svalue
slider
slider
Editable Text callback edit1_Callback
svalue = get(h,'String');
nvalue = str2num(svalue)
if nvalue > 10
nvalue = 10;
set(h,'String','10');
elseif nvalue < 0
nvalue = 0
set(h,'String','0');
elseif nvalue == [ ]
nvalue = 0
set(h,'String','0');
end

set(handles.slider1,'Value', nvalue);

String Editable Text


String nvalue if
nvalue
String Editable Text ( 10
String)
Value Slider Editable Text

GUI
GUI save file Editor/Debugger
Activate GUI GUI

Getting Start with GUIDE 281


15.3 Check Box, List Box Popup Menu
Check Box, List Box Popup Menu GUI
Check Box, List Box
Popup Menu

Check Box Value


Value 1 Value 0
List Box Value

1 Value 1 2 Value 2
String List Box String
Vector

Popup Menu Value List box


String Popup Menu Vector

List Box Popup Menu
List Box
GUI Popup Menu GUI

GUI

282 Getting Start with GUIDE



 Product Popup Menu

 /


List Box
 Static Text

GUIDE Layout Editor


Tag

 String Static Text Tag Static Text

Product Result

Getting Start with GUIDE 283


 Check Box String At Work Tag Work Value 0
 Check Box String At Home Tag Home Value 0
 Popup Menu Tag Popup1 Sting
String

OK Property Inspector
Value 1
 List Box Tag HomeList Sting
String

284 Getting Start with GUIDE


OK Property Inspector
Value 1 Enable
off
 Figure Name Product Selection

Save Activate GUI


Save GUI Save File
MATLAB product OK
MATLAB product.fig product.m
activate GUI MATLAB GUI
Editor/Debugger product.m

GUI
GUI
GUI Callback Subfunction
Subfunction
Subfunction Callback
Subfunction Subfunction manager
Application M-file product.m

% ----------------------------------------------------------------
function manager(handles)

nselect = get(handles.Popup1,'Value');
pop_string = get(handles.Popup1,'String');
ProSelect = pop_string(nselect);
string_display = strcat('You have selected',ProSelect);

if get(handles.Work,'Value') == 1;
string_display =strcat(string_display,'for use it at work');
if get(handles.Home,'Value') ==1;
Nselect = get(handles.HomeList,'Value');
list_string = get(handles.HomeList,'String');
HomeSelect = list_string(Nselect);
string_display=strcat(string_display,'and use it at home',
HomeSelect);

Getting Start with GUIDE 285


end
elseif get(handles.Home,'Value') ==1;
nselect = get(handles.HomeList,'Value');
list_string = get(handles.HomeList,'String');
HomeSelect = list_string(nselect);
string_display=strcat(string_display,'and use it at home',
HomeSelect);
end

set(handles.Result,'String',string_display);

subfunction input handles


handle Popup Menu
String
strcat String

string Popup Menu List Box



if elseif end Logic
check box
string list box
Subfuction Application M-file
manager(handles) Subfunction Check Box At Home

List Box

% ----------------------------------------------------------------
function varargout=Home_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.Home.
if get(h,'Value') == 1
set(handles.HomeList,'Enable','on');
else
set(handles.HomeList,'Enable','off');
end
manager(handles)
% ----------------------------------------------------------------

Enable on
off

GUI

286 Getting Start with GUIDE


GUI save file Editor/Debugger
Activate GUI GUI

15.4 Object Handle GUI


GUI GUIDE FIG-file M-file
Structure handles field Tag
field handles
MATLAB handles
GUI
handle handles
handle
handles GUIDE uicontrol
layout GUI
GUI
Subfunction handles
Subfunction

Subfunction GUI GUI

GUI guihandles guidata

handles = guihandles(fig); guihandles Structure


handle fig field
handles handle fig field Tag

guidata[fig, handles] handles


guidata
MATLAB handles

GUI handles

Getting Start with GUIDE 287


Subfunction
handles guidata
Callback Callback
Subfunction Application M-file Subfunction
handles

GUI

GUIDE Layout Editor


GUI Uicontrol


GUI

Uicontrol Property name Property value

288 Getting Start with GUIDE


Figure Name My Graph
Axes Next Plot Replacechildren
Editable Text () Tag Xmin
String 0
Blackgroundcolor
Editable Text () Tag Xmax
String 5
Blackgroundcolor
Push Button Tag Sine
(sin(x)) String sin (x)
Uicontrol Property name Property value
Push Button Tag Cos
(cos(x))
String cos(x)
Push Button Tag XSine
(x sin(x)) String x sin (x)
Push Button Tag XCos
(x cos(x)) String x cos (x)
Toggle Button Tag GridOn
String Grid On
Value 0
Popup Menu Tag Popupmenu2
String Blue, Green, Red, Yellow, Black,
Pink
(
)
Static Text String

Save Activate GUI


Save GUI Save File
MATLAB My_graph OK
MATLAB My_graph.fig My_graph.m

Getting Start with GUIDE 289


activate GUI MATLAB GUI
Editor/Debugger My_graph.m

GUI
subfunction application M-file

1 subfunction push button


Sine code

1 function varargout=Sine_Callback(h,eventdata,handles,varargin)
2 % Stub for Callback of the uicontrol handles.Sine.
3 set(handles.figure1,'HandleVisibility','on');
4 xmin = str2num(get(handles.Xmin,'String'));
5 xmax = str2num(get(handles.Xmax,'String'));
6 x=linspace(xmin,xmax,200);
7 y=sin(x);
8 LinePlot=plot(x,y);
9 handles.LineX = LinePlot;
10 guidata(gcbo, handles);
11 popupmenu2_Callback(h, eventdata, handles, varargin);
12 set(handles.figure1,'HandleVisibility','off');

Code
1 function, 3 GUI
handle handle
plot GUI set ON set Callback
Callback Command windows
set ON On
plot Command windows
4 5 string edit text
6, 7 8
handle LinePlot
9 field handles field
LineX handle
10 gcbo
get callback object push button handles.figure1 handle
GUI GUI
gcbo MATLAB parent

290 Getting Start with GUIDE


handles
Subfunction
11 function popup menu
12 handle MATLAB

Push Button plot


Code
function varargout=Cosine_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Cosine.
set(handles.figure1,'HandleVisibility','on');
xmin = str2num(get(handles.Xmin,'String'));
xmax = str2num(get(handles.Xmax,'String'));
x=linspace(xmin,xmax,200);
y=cos(x);
LinePlot=plot(x,y);
handles.LineX = LinePlot;
guidata(gcbo, handles);
popupmenu2_Callback(h, eventdata, handles, varargin);
set(handles.figure1,'HandleVisibility','off');

% ----------------------------------------------------------------
function varargout=Xsine_Callback(h, eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.Xsine.
set(handles.figure1,'HandleVisibility','on');
xmin = str2num(get(handles.Xmin,'String'));
xmax = str2num(get(handles.Xmax,'String'));
x=linspace(xmin,xmax,200);
y=x.*sin(x);
LinePlot=plot(x,y);
handles.LineX = LinePlot;
guidata(gcbo, handles);
popupmenu2_Callback(h, eventdata, handles, varargin);
set(handles.figure1,'HandleVisibility','off');

% ----------------------------------------------------------------
function varargout=Xcosine_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.Xcosine.
set(handles.figure1,'HandleVisibility','on');
xmin = str2num(get(handles.Xmin,'String'));
xmax = str2num(get(handles.Xmax,'String'));
x=linspace(xmin,xmax,200);
y=x.*cos(x);
LinePlot=plot(x,y);
handles.LineX = LinePlot;
guidata(gcbo, handles);
popupmenu2_Callback(h, eventdata, handles, varargin);
set(handles.figure1,'HandleVisibility','off');
% ----------------------------------------------------------------

Popup menu Code


% ----------------------------------------------------------------
function varargout=popupmenu2_Callback(h,eventdata,handles,varargin)
% Stub for Callback of the uicontrol handles.popupmenu2.

Getting Start with GUIDE 291


col = get(handles.popupmenu2,'Value');
LinePlot=handles.LineX;
if col == 1
set(LinePlot,'Color',[0 0 1]');
elseif col == 2
set(LinePlot,'Color',[0 1 0]');
elseif col == 3
set(LinePlot,'Color',[1 0 0]');
elseif col == 4
set(LinePlot,'Color',[1 1 0]');
elseif col == 5
set(LinePlot,'Color',[0 0 0]');
elseif col == 6
set(LinePlot,'Color',[1 0 1]');
end
% ----------------------------------------------------------------

handles.LineX
RGB

Callback Toggle Button Code


% ----------------------------------------------------------------
function varargout=GridOn_Callback(h,eventdata, handles, varargin)
% Stub for Callback of the uicontrol handles.GridOn.
set(handles.figure1,'HandleVisibility','on');
status = get(h,'Value');
if status == 0
set(h,'String','Grid On');
grid off
else
set(h,'String','Grid Off');
grid on
end
set(handles.figure1,'HandleVisibility','off');
% ----------------------------------------------------------------

Toggle
code handle grid
on grid off

Subfucntion Callback Editable Text Max Min



Callback

GUI
Save Application M-file activate GUI

292 Getting Start with GUIDE


GUI
GUI
error plot graph
handles.LineX
GUI handles
GUI
Application M-file guidata guidata
guidata

set(fig,'HandleVisibility','on');
xmin = str2num(get(handles.Xmin,'String'));
xmax = str2num(get(handles.Xmax,'String'));
x=linspace(xmin,xmax,200);
y=sin(x);
LinePlot=plot(x,y);
handles.LineX = LinePlot;
guidata(fig, handles);
set(fig,'HandleVisibility','off');

handles GUI
Save Application M-file activate GUI

Getting Start with GUIDE 293



Subfunction
GUI
GUI
GUI

294 Getting Start with GUIDE


MATLAB
MATLAB MATLAB function
MATLAB
function MATLAB
function help

 General Purpose Commands

Managing Commands and Functions


addpath Add directories to MATLABs search path
doc Load hypertext documentation
help Online help for MATLAB functions and M-files
lasterr Last error message
lookfor Keyword search through all help entries
path Control MATLABs directory search path
profile Measure and display M-file execution profiles
rmpath Remove directories from MATLABs search path
type List file
version MATLAB version number
what Directory listing of M-files, MAT-files, and MEX-files
whatsnew Display README files for MATLAB and toolboxes
which Locate functions and files

Managing Variables and the Workspace


clear Remove items from memory
disp Display text or array
length Length of vector
load Retrieve variables from disk
pack Consolidate workspace memory
save Save workspace variables on disk
size Array dimensions
who, whos List directory of variables in memory

Controlling the Command Window


echo Echo M-files during execution
format Control the output display format
more Control paged output for the command window

Working with Files and the Operating Environment


cd Change working directory
delete Delete files and graphics objects
diary Save session in a disk file
dir Directory listing
edit Edit an M-file
fullfile Build full filename from parts
inmem Functions in memory
MATLABroot Root directory of MATLAB installation

Appendix 295
tempdir Return the name of the systems temporary directory.
tempname Unique name for temporary file
! Execute operating system command

Starting and Quitting MATLAB


MATLABrc MATLAB startup M-file
quit Terminate MATLAB .
startup MATLAB startup M-file

Operators and Special Characters


+ Plus
- Minus
* Matrix multiplication
.* Array multiplication
^ Matrix power
.^ Array power
kron Kronecker tensor product.
\ Backslash or left division.
/ Slash or right division
./ and .\ Array division, right and left
: Colon
() Parentheses
[] Brackets
{} Curly braces
. Decimal point
... Continuation
, Comma
; Semicolon.
% Comment
! Exclamation point
' Transpose and quote
.' Nonconjugated transpose
= Assignment.
== Equality.
<> Relational operators
& Logical AND .
| Logical OR.
~ Logical NOT
xor Logical EXCLUSIVE OR

Logical Functions
all Test to determine if all elements are nonzero
any Test for any nonzeros
exist Check if a variable or file exists
find Find indices and values of nonzero elements
is* Detect state.
*isa Detect an object of a given class.
logical Convert numeric values to logical

 Language Constructs and Debugging

MATLAB as a Programming Language


builti Execute builtin function from overloaded method
eval Interpret strings containing MATLAB expressions
feval Function evaluation
function Function M-files
global Define global variables
nargchk Check number of input arguments

296 Appendix
script Script M-files

Control Flow
break Break out of flow control structures
case Case switch.
else Conditionally execute statements
elseif Conditionally execute statements
end Terminate for, while, switch, and if statements or indicate last index
error Display error messages
for Repeat statements a specific number of times
if Conditionally execute statements
otherwise Default part of switch statement
return Return to the invoking function
switch Switch among several cases based on expression
warning Display warning message
while Repeat statements an indefinite number of times

Interactive Input
input Request user input.
keyboard Invoke the keyboard in an M-file.
menu Generate a menu of choices for user input
pause Halt execution temporarily

Object-Oriented Programming
class Create object or return class of object
double Convert to double precision
inferiorto Inferior class relationship
inline Construct an inline object.
isa Detect an object of a given class
superiorto Superior class relationship
uint8 Convert to unsigned 8-bit integer

Debugging
dbclear Clear breakpoints
dbcont Resume execution
dbdown Change local workspace context
dbmex Enable MEX-file debugging
dbquit Quit debug mode
dbstack Display function call stack
dbstatus List all breakpoints.
dbstep Execute one or more lines from a breakpoint.
dbstop Set breakpoints in an M-file function
dbtype List M-file with line numbers
dbup Change local workspace context

 Elementary Matrices and Matrix Manipulation

Elementary Matrices and Arrays


eye Identity matrix
linspace Generate linearly spaced vectors
logspace Generate logarithmically spaced vectors
ones Create an array of all ones
rand Uniformly distributed random numbers and arrays
randn Normally distributed random numbers and arrays
zeros Create an array of all zeros
: (colon) Regularly spaced vector

Special Variables and Constants

Appendix 297
ans The most recent answer
computer Identify the computer on which MATLAB is running
eps Floating-point relative accuracy
flops Count floating-point operations
i Imaginary unit.
Inf Infinity
inputname Input argument name
j Imaginary unit.
NaN Not-a-Number
nargin, Number of function arguments.
nargout
pi Ratio of a circles circumference to its diameter,
realmax Largest positive floating-point number
realmin Smallest positive floating-point number
varargin, Pass or return variable numbers of arguments.
varargout

Time and Dates


calendar Calendar.
clock Current time as a date vector
cputime Elapsed CPU time .
date Current date string
datenum Serial date number
datestr Date string format
datevec Date components
eomday End of month.
etime Elapsed time.
now Current date and time
tic, toc Stopwatch timer .
weekday Day of the week .

Matrix Manipulation
cat Concatenate arrays
diag Diagonal matrices and diagonals of a matrix
fliplr Flip matrices left-right
flipud Flip matrices up-down
repmat Replicate and tile an array.
reshape Reshape array .
rot90 Rotate matrix 90 degrees.
tril Lower triangular part of a matrix.
triu Upper triangular part of a matrix .
: (colon) Index into array, rearrange array .

Specialized Matrices
compan Companion matrix .
gallery Test matrices .
hadamard Hadamard matrix . .
hankel Hankel matrix .
hilb Hilbert matrix .
invhilb Inverse of the Hilbert matrix .
magic Magic square
pascal Pascal matrix .
toeplitz Toeplitz matrix .
wilkinson Wilkinsons eigenvalue test matrix

Elementary Math Functions


abs Absolute value and complex magnitude
acos, acosh Inverse cosine and inverse hyperbolic cosine
acot, acoth Inverse cotangent and inverse hyperbolic cotangent

298 Appendix
acsc, acsch Inverse cosecant and inverse hyperbolic cosecant
angle Phase angle
asec, asech Inverse secant and inverse hyperbolic secant
asin, asinh Inverse sine and inverse hyperbolic sine
atan, atanh Inverse tangent and inverse hyperbolic tangent
atan2 Four-quadrant inverse tangent.
ceil Round toward infinity.
conj Complex conjugate
cos, cosh Cosine and hyperbolic cosine.
cot, coth Cotangent and hyperbolic cotangent.
csc, csch Cosecant and hyperbolic cosecant
exp Exponential
fix Round towards zero
floor Round towards minus infinity
gcd Greatest common divisor
imag Imaginary part of a complex number
lcm Least common multiple
log Natural logarithm
log2 Base 2 logarithm and dissect floating-point numbers into exponent and
mantissa
log10 Common (base 10) logarithm
mod Modulus (signed remainder after division)
real Real part of complex number
rem Remainder after division
round Round to nearest integer
sec, sech Secant and hyperbolic secant
sign Signum function
sin, sinh Sine and hyperbolic sine
sqrt Square root
tan, tanh Tangent and hyperbolic tangent

Specialized Math Functions


airy Airy functions
besselh Bessel functions of the third kind (Hankel functions)
besseli, besselk
Modified Bessel functions
besselj, bessely Bessel functions
beta, betainc, Beta functions
betaln
ellipj Jacobi elliptic functions
ellipke Complete elliptic integrals of the first and second kind
erf, erfc, erfcx, Error functions
erfinv
expint Exponential integral
gamma, Gamma functions
gammainc,
gammaln
legendre Associated Legendre functions.
pow2 Base 2 power and scale floating-point numbers
rat, rats Rational fraction approximation

Coordinate System Conversion


cart2pol Transform Cartesian coordinates to polar or cylindrical
cart2sph Transform Cartesian coordinates to spherical
pol2cart Transform polar or cylindrical coordinates to Cartesian
sph2cart Transform spherical coordinates to Cartesian

 Matrix Functions - Numerical Linear Algebra

Appendix 299
Matrix Analysis
cond Condition number with respect to inversion
condeig Condition number with respect to eigenvalues
det Matrix determinant
norm Vector and matrix norms
null Null space of a matrix
orth Range space of a matrix
rank Rank of a matrix
rcond Matrix reciprocal condition number estimate
rref, rrefmovie Reduced row echelon form.
subspace Angle between two subspaces.
trace Sum of diagonal elements.

Linear Equations
\/ Linear equation solution.
chol Cholesky factorization
inv Matrix inverse
lscov Least squares solution in the presence of known covariance
lu LU matrix factorization.
nnls Nonnegative least squares
pinv Moore-Penrose pseudoinverse of a matrix
qr Orthogonal-triangular decomposition

Eigenvalues and Singular Values


balance Improve accuracy of computed eigenvalues
cdf2rdf Convert complex diagonal form to real block diagonal form
eig Eigenvalues and eigenvectors
hess Hessenberg form of a matrix
poly Polynomial with specified roots
qz QZ factorization for generalized eigenvalues
rsf2csf Convert real Schur form to complex Schur form.
schur Schur decomposition
svd Singular value decomposition

Matrix Functions
expm Matrix exponential
funm Evaluate functions of a matrix
logm Matrix logarithm
sqrtm Matrix square root

Low Level Functions


qrdelete Delete column from QR factorization.
qrinsert Insert column in QR factorization.

 Data Analysis and Fourier Transform Functions

Basic Operations
convhull Convex hull
cumprod Cumulative product
cumsum Cumulative sum
cumtrapz Cumulative trapezoidal numerical integration
delaunay Delaunay triangulation
dsearch Search for nearest point
factor Prime factors
inpolygon Detect points inside a polygonal region
max Maximum elements of an array
mean Average or mean value of arrays

300 Appendix
median Median value of arrays
min Minimum elements of an array
perms All possible permutations
polyarea Area of polygon
primes Generate list of prime numbers
prod Product of array elements
sort Sort elements in ascending order.
sortrows Sort rows in ascending order
std Standard deviation
sum Sum of array elements
trapz Trapezoidal numerical integration
tsearch Search for enclosing Delaunay triangle
voronoi Voronoi diagram.

Finite Differences
del2 Discrete Laplacian
diff Differences and approximate derivatives
gradient Numerical gradient

Correlation
corrcoef Correlation coefficients.
cov Covariance matrix

Filtering and Convolution


conv Convolution and polynomial multiplication
conv2 Two-dimensional convolution.
deconv Deconvolution and polynomial division.
filter Filter data with an infinite impulse response (IIR) or finite impulse response
(FIR) filter
filter2 Two-dimensional digital filtering

Fourier Transforms
abs Absolute value and complex magnitude
angle Phase angle
cplxpair Sort complex numbers into complex conjugate pairs
fft One-dimensional fast Fourier transform
fft2 Two-dimensional fast Fourier transform
fftshift Move zeroth lag to center of spectrum.
ifft Inverse one-dimensional fast Fourier transform
ifft2 Inverse two-dimensional fast Fourier transform
nextpow2 Next power of two
unwrap Correct phase angles

Vector Functions
cross Vector cross product
intersect Set intersection of two vectors
ismember Detect members of a set
setdiff Return the set difference of two vectors
setxor Set exclusive-or of two vectors
union Set union of two vectors
unique Unique elements of a vector

 Polynomial and Interpolation Functions

Polynomials
conv Convolution and polynomial multiplication
deconv Deconvolution and polynomial division
Poly Polynomial with specified roots

Appendix 301
polyder Polynomial derivative
polyeig Polynomial eigenvalue problem
polyfit Polynomial curve fitting
polyval Polynomial evaluation
polyvalm Matrix polynomial evaluation
residue Convert between partial fraction expansion and polynomial coefficients
roots Polynomial roots

Data Interpolation
griddata Data gridding.
interp1 One-dimensional data interpolation (table lookup)
interp2 Two-dimensional data interpolation (table lookup)
interp3 Three-dimensional data interpolation (table lookup)
interpft One-dimensional interpolation using the FFT method
interpn Multidimensional data interpolation (table lookup).
meshgrid Generate X and Y matrices for three-dimensional plots
ndgrid Generate arrays for multidimensional functions and interpolation
spline Cubic spline interpolation

Function Functions Nonlinear Numerical Methods


dblquad Numerical double integration
fmin Minimize a function of one variable
fmins Minimize a function of several variables.
fzero Zero of a function of one variable .
ode45, ode23, Solve differential equations
ode113,
ode15s, ode23s
odefile Define a differential equation problem for ODE solvers
odeget Extract properties from options structure created with odeset
odeset Create or alter options structure for input to ODE solvers
quad, quad8 Numerical evaluation of integrals

 Sparse Matrix Functions

Elementary Sparse Matrices


spdiags Extract and create sparse band and diagonal matrices
speye Sparse identity matrix
sprand Sparse uniformly distributed random matrix
sprandn Sparse normally distributed random matrix.
sprandsym Sparse symmetric random matrix

Full to Sparse Conversion


find Find indices and values of nonzero elements
full Convert sparse matrix to full matrix
sparse Create sparse matrix
spconvert Import matrix from sparse matrix external format

Working with Nonzero Entries of Sparse Matrices


nnz Number of nonzero matrix elements
nonzeros Nonzero matrix elements
nzmax Amount of storage allocated for nonzero matrix elements
spalloc Allocate space for sparse matrix
spfun Apply function to nonzero sparse matrix elements
spones Replace nonzero sparse matrix elements with ones

Visualizing Sparse Matrices


spy Visualize sparsity pattern

302 Appendix
Reordering Algorithms
colmmd Sparse column minimum degree permutation.
colperm Sparse column permutation based on nonzero count
dmperm Dulmage-Mendelsohn decomposition
randperm Random permutation .
symmmd Sparse symmetric minimum degree ordering.
symrcm Sparse reverse Cuthill-McKee ordering.

Norm, Condition Number, and Rank


condest 1 norm matrix condition number estimate
normest 2 norm estimate.

Sparse Systems of Linear Equations


bicg BiConjugate Gradients method .
bicgstab BiConjugate Gradients Stabilized method
cgs Conjugate Gradients Squared method .
cholinc Incomplete Cholesky factorizations .
gmres Generalized Minimum Residual method (with restarts).
luinc Incomplete LU matrix factorizations .
pcg Preconditioned Conjugate Gradients method .
qmr Quasi-Minimal Residual method .

Sparse Eigenvalues and Singular Values


eigs Find a few eigenvalues and eigenvectors .
svds A few singular values.

Miscellaneous
spparms Set parameters for sparse matrix routines .

 Sound Processing Functions

General Sound Functions


sound Convert vector into sound

SPARCstation-specific Sound Functions


auread Read NeXT/SUN (.au) sound file
auwrite Write NeXT/SUN (.au) sound file

.WAV Sound Functions


wavread Read Microsoft WAVE (.wav) sound file
wavwrite Write Microsoft WAVE (.wav) sound file .

 Character String Functions

General
abs Absolute value and complex magnitude
eval Interpret strings containing MATLAB expressions
strings MATLAB string handling

String Manipulation
deblank Strip trailing blanks from the end of a string
findstr Find one string within another
lower Convert string to lower case
strcat String concatenation
strcmp Compare strings.
strjust Justify a character array.

Appendix 303
strmatch Find possible matches for a string
strncmp Compare the first n characters of two strings
strrep String search and replace
strtok First token in string
strvcat Vertical concatenation of strings
upper Convert string to upper case

String to Number Conversion


char Create character array (string)
int2str Integer to string conversion
mat2str Convert a matrix into a string
num2str Number to string conversion
sprintf Write formatted data to a string
sscanf Read string under format control
str2num String to number conversion

Radix Conversion
bin2dec Binary to decimal number conversion
dec2bin Decimal to binary number conversion
dec2hex Decimal to hexadecimal number conversion
hex2dec IEEE hexadecimal to decimal number conversion.
hex2num Hexadecimal to double number conversion.

 Low-Level File I/O Functions

File Opening and Closing


fclose Close one or more open files
fopen Open a file or obtain information about open files

Unformatted I/O
fread Read binary data from file
fwrite Write binary data to a file.

Formatted I/O
fgetl Return the next line of a file as a string without line terminator(s)
fgets Return the next line of a file as a string with line terminator(s)
fprintf Write formatted data to file
fscanf Read formatted data from file

File Positioning
feof Test for end-of-file
ferror Query MATLAB about errors in file input or output
frewind Rewind an open file
fseek Set file position indicator
ftell Get file position indicator.

String Conversion
sprintf Write formatted data to a string .
sscanf Read string under format control

Specialized File I/O


dlmread Read an ASCII delimited file into a matrix.
dlmwrite Write a matrix to an ASCII delimited file
imfinfo Return information about a graphics file
imread Read image from graphics file
imwrite Write an image to a graphics file
wk1read Read a Lotus123 WK1 spreadsheet file into a matrix
wk1write Write a matrix to a Lotus123 WK1 spreadsheet file.

304 Appendix
Bitwise Functions
bitand Bit-wise AND.
bitcmp Complement bits
bitor Bit-wise OR
bitmax Maximum floating-point integer
bitset Set bit
bitshift Bit-wise shift.
bitget Get bit
bitxor Bit-wise XOR

Structure Functions
fieldnames Field names of a structure
getfield Get field of structure array
rmfield Remove structure fields
setfield Set field of structure array
struct Create structure array
struct2cell Structure to cell array conversion

Object Functions
class Create object or return class of object
isa Detect an object of a given class

Cell Array Functions


cell Create cell array
cellstr Create cell array of strings from character array
cell2struct Cell array to structure array conversion
celldisp Display cell array contents
cellplot Graphically display the structure of cell arrays
num2cell Convert a numeric array into a cell array

Multidimensional Array Functions


cat Concatenate arrays
flipdim Flip array along a specified dimension
ind2sub Subscripts from linear index.
ipermute Inverse permute the dimensions of a multidimensional array
ndgrid Generate arrays for multidimensional functions and interpolation
ndims Number of array dimensions
permute Rearrange the dimensions of a multidimensional array
reshape Reshape array
shiftdim Shift dimensions
squeeze Remove singleton dimensions
sub2ind Single index from subscripts

Appendix 305


MATLAB
The Student Edition of MATLAB Version 5 : Users Guide, Prentice Hall, 1997.
Biran, A. and Breiner, M., MATLAB for Engineers, Addison-Wesley, 1995.
Enander, E. P., et al, The MATLAB Handbook, Addison-Wesley, 1996.
Etter, D.M., Engineering Problem Solving with MATLAB, 2nd ed., Prentice Hall, 1997.
MATLAB Language Reference Manual : Version 5, MathWorks Inc., 1996.
MATLAB Graphics Reference Manual : Version 5, MathWorks Inc., 1996.
MATLAB Notebook Users Guide : Version 5, MathWorks Inc., 1996.

Gerald, C.F. and Wheatley, P.O., Applied Numerical Analysis, 5th ed., Addison-Wesley, 1994.
Kreyszig, E., Advance Engineering Mathematics, 7th ed., John Wiley, 1993.

Inman, D.J., Engineering Vibration, Prentics Hall, 1994.


Thomson, W.T., Theory of Vibration with Applications, 4th ed., Prentics Hall, 1993.
Rao, S. S., Mechanical Vibrations, 3rd ed., Addison-Wesley, 1995.
Steidel, R. F., An Introduction to Mechanical Vibrations, 3rd ed., John Wiley, 1989.
Kelly, S.G., Mechanical Vibrations, McGraw-Hill, 1993.
Ferguson, C. R., Internal Combustion Engine, John Wiley, 1986.
Heywood, J. B., Internal Combustion Engine Fundamentals, McGraw-Hill, 1988.
Shames, I. V., Mechanics of Fluids, 3rd ed., McGraw-Hill, 1992.
Janna, W. S., Introduction to Fluid Mechanics, 3rd ed., PWS, 1993.
Anderson, J. D., Fundamental of Aerodynamics, 2nd ed., McGraw-Hill, 1991.
Smith, W. F., Principles of Materials Science and Engineering, 3rd ed., McGraw-Hill, 1996.
Shames, I. V., Introduction to Solid Mechanics, 2nd ed., Prentics Hall, 1989.

Web Site: www.mathworks.com

Appendix 306

You might also like