Professional Documents
Culture Documents
Matlab Book
Matlab Book
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
" ________________________________________________ 76
4 M-FILE ______________________________________________79
4.1 M-File_______________________________________________________________ 79
4.2 Script Files & Function Files _______________________________________________ 80
4.3 M-File ___________________________________ 83
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
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
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
MATLAB function
function function
MATLAB
C, FORTRAN
MATLAB
2 3
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
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
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
Launch Pad
toolbox MATLAB
desktop
desktop (docking)
desktop desktop shortcut
context menus desktop
Preferences File Command
Window desktop Help
Preferences
Introduction to MATLAB
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
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
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
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
MATLAB
(Workspace) MATLAB
M-file load
MATLAB 6.0 Workspace Browser
Desktop Tool version MATLAB who whos
Command Windows Workspace Browser
Introduction to MATLAB
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
12
Basic Operation
Editor/Debugger
Editor/Debugger
M-file
s Graphic Windows
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
= B*C(1,2)
New
Airtime = 20
% comment MATLAB
^ MATLAB
Enter key ( Enter
key )
o MATLAB
p Function Keys
MATLAB keys
Introduction to MATLAB
15
Ctrl-p
Ctrl-f
Ctrl-b
Del Backspace
Ctrl-l Ctrl-
Ctrl-r Ctrl-
Ctrl-a Home
End
Ctrl-n
Ctrl-k
1
1
1
1
1
MATLAB
help
16
Basic Operation
Introduction to MATLAB
17
External Interfaces/API C
Fortran Java, , serial port I/O, ActiveX DDE
s Reference
syntax
Function
By Category Alphabetical List of Functions
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
0
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
1 2
a=
3 4
a = [1 2;3 4]
a =
1 2
3 4
row
enter
a =[1, 2
3, 4]
a matrix [1 x 6]
Basic Operation
21
b = [0 1 2 3]
MATLAB (echo)
a = [1, 2, 3]
MATLAB
a =
1
MATLAB semicolon
a = [1, 2, 3];
echo
MATLAB ans
0 MATLAB
echo echo
row 1 column 2 2 5
a(1,2) = 5
matrix a
a =
1 5
3 4
a(3) = 5
a
a = [1 2 5]
22
Basic Operation
a = [1 2 3] a(7) = 5
a = [1 2 0 0 0 0 5]
MATLAB 3
who
whos , byte
size
matrix array a = 13
2
,
4
size(a)
ans =
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
= x(2,:)
b row 2 x
b = [4 5 6]
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
e = a(:)
e =
1
4
9
2
5
7
3
24
Basic Operation
6
8
Matrix matrix 0 x 0
a = [ ];
= 10:1:0;
matrix
matrix element
1 2 3
a=
4 5 6
1 4
a = 2 5
3 6
T
MATLAB transpose (
'
) a'
a = [1 2 3;4 5 6]
a =
1
2
3
4
5
6
b = a'
b =
1
2
3
4
5
6
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
NaN
clock
date
eps
ans
infinity
Not-a-Number (undefined) 0 0
Computer
format -- 1-jan-97
floating-point precision computer
r Matrix MATLAB
Matrix MATLAB matrix
rand(m,n)
hilb(N)
matrix [m x n] element
0 1
rand(m) square matrix
Hilbert matrix matrix [N x N] element
1
(i + j 1)
magic(N)
zeros(m,n)
ones(m,n)
eye(m,n)
square matrix [N x N] 1 N2
element row, column diagonal
N 1, 3, 4, 5,
matrix [m x n] element
matrix [m x n] element 1
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
matrix 11
ones(2)
1
1
a=eye(3,4)
a =
1
0
0
0
1
0
0
0
1
0
0
0
linspace(1,3,10)
ans =
Columns 1 through 7
1.0000
1.2222 1.4444 1.6667
Columns 8 through 10
2.5556
2.7778
3.0000
1.8889
2.1111
2.3333
s String Variable
string
quotation '
Str1='Tom';
Str2='Pookie';
string
function
matrix element string
matrix column
row blank space string
A B =
a b N element A B
i i
i =1
Basic Operation
27
dot(A,B)
dot(A,B)
ans =
32
o Matrix
C =2*A
C =
2
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^3
A^2
A*A
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
MATLAB inv
Basic Operation
29
inv(a)
o Rank of Matrix
row matrix rank matrix
1 2 3
a=
2 4 6
p Determinant of Matrix
Determinant square matrix scalar matrix determinant
square matrix a MATLAB
det(a)
determinant a
a=[1 2 3; 2 7 6; 5 4 8];
det(a)
ans =
-21
q Matrix
30
Basic Operation
x= A B
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
1
Technique
r Matrix Decomposition
Basic Operation
31
1 2 3
U = 0 4 5
0 0 6
A matrix
A = LU
MATLAB
[L,U]= lu(A)
-6.0000
-1.0000
0
1.0000
8.0000
2.5000
0 LU-decomposition
LU-decomposition permutes lower
triangular factor
32
0
1.0000
1.0000
8.0000
2.5000
Basic Operation
PA = LU
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
0
-8.2369
-0.3922
-7.4524
-1.5689
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
B
= [1 2 3 4];
= [2 4 4 5];
A * B matrix C c
= ai bi
array operation . *
C
A.*B
= A./B
= A.^B
34
Basic Operation
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
MATLAB
(1)
(2)
(2)
(3)
0
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)
triu(A)
triu(A,k)
tril(A)
tril(A,k)
36
rot90(A)
ans =
3
2
1
4
2
0
8
6
3
tril(A)
ans =
1
0
3
0
2
6
0
0
8
triu(A,2)
ans =
0
0
0
0
0
0
3
0
0
diag(A)
ans =
1
2
8
flipud(A)
ans =
3
0
1
6
2
2
8
4
3
Basic Operation
x=[1 3 5; 4 2 8]
x =
1 3 5
4 2
8
y=[7 1 4;2 0 1]
y =
7
1
2
0
4
1
z=[4 2 1;3 6 9]
z =
4
2
3
6
1
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
x, y, z 2 x 3 d 2 x 3 x 3 cat
Cat(dims,A1,A2,A3,...)
Basic Operation
37
ipermute(A,order)
shiftdim(A,n)
B = squeeze(A)
dimension A
A B order
order vector B
element
permute(A, order)
dimension A n
dimension 1 B element
A 1
matrix vector
vector
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
p=squeeze(p);
size(p)
ans =
2
4
3
1-1-3 g
g(1,1,3)
ans =
5
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]
[1x10 double]
size(x)
ans =
2
5]
'Text Only'
x
class(x)
ans =
cell
4.4444
5.5556
6.6667
cell
x{1,2}
ans =
5
5+4i]}
o Cell Array
40
Basic Operation
x
x =
[2x2 double]
[1x10 double]
y
y =
[2x2 double]
[2x3 char ]
5]
'Text Only'
[2x2 double]
[1x2 double]
a=[x y]
a =
[2x2 double]
[1x10 double]
b=[x;y]
b =
[2x2
[1x10
[2x2
[2x3
[
5]
'Text Only'
double]
double]
double]
char ]
[2x2 double]
[2x3 char ]
[2x2 double]
[1x2 double]
[
5]
'Text Only'
[2x2 double]
[1x2 double]
reshape
c=reshape(b,2,4)
c =
[2x2 double] [2x2 double]
[1x10 double] [2x3 char ]
[ 5] [2x2 double]
'Text Only'
[1x2 double]
cell array
cell cell
Basic Operation
41
c
c =
[2x2 double] [2x2 double]
[ 5] [2x2 double]
[1x10 double]
[2x3 char ]
'Text Only'
c{1,4}
ans =
2
5
[1x2 double]
3
7
c{1,4}(2,1)
ans =
5
[p q] = deal(c{1,2:3})
p =
1
3
5
6
q =
5
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
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
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';
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
MATLAB
format short
Basic Operation
22.1234
45
format long
format bank
format short e
format long e
format +
15
2
4 10
15 10
+ , -
22.123456789012345
22.12
2.123 e+01
2.12345678901234 e+01
+
MATLAB echo
MATLAB
disp
A disp(A) A disp(Display)
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
Total force is
10.000000 newtons
%f newtons \n,A)
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
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))
A matrix plot coordinate (j,A1j), (j,A2j),.. j index
plot(A)
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 vector x Matrix A A m x n vector x m
plot(A,x)
plot x column A vector x n plot x
row A
plot column B column A A B m x n
plot(A,B)
plot curve n m coordinate
plot(x,y,str)
48
y = yellow
g = green
m = magenta
.
*
X
-
--
-. dash-dotted
Basic Operation
b = blue
c = cyan
w = white
r = read
k = black
O
+
S
D
^
V
>
<
P
H
: dotted
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,...)
Graphics window
character string txt ='charactor string
'
title(txt)
xlabel(txt)
ylabel(txt)
Basic Operation
string txt
string txt x x
string txt y y
49
zlabel(txt)
text(x,y,txt)
( 3 ) z
string txt plot coordinate (x,y)
Text vector string
vector x y txti (xi, yi)
text(x,y,txt,sc)
Legend(txt1,txt2,...,pos)
legend off
0 =
1 = ( MATLAB
)
2 =
3 =
4 =
-1 =
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])
axis(axis)
( z
3 )
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
q Graphic
graphic window
figure
graphic window MATLAB
plot
clf
clc
Basic Operation
graphic window
command window
51
hold on
hold off
hold
ishold
r Subplot
graphic window
MATLAB 1 Graphic window
sub - plot graphic window subplot
subplot(m,n,p)
subplot
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
-0.2
-0.4
-0.6
-0.8
-1
0
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
First Graph
Second Graph
4.5
4
3.5
3
2.5
2
1.5
1
10
11
12
13
14
15
This is X-axis title
16
17
18
54
Basic Operation
30
20
10
-10
-20
First Graph
Second Graph
-30
0
6
8
This is X-axis title
10
12
14
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
subplot(2,2,2);
semilogx(x,y)
title('This is the graph at position
grid on
subplot(2,2,3);
semilogy(x,y)
title('This is the graph at position
subplot(2,2,4);
loglog(x,y)
title('This is the graph at position
grid on
1 of 2x2')
2 of 2x2')
3 of 2x2')
4 of 2x2')
Figure Windows
X=linspace(0,4*pi);
Basic Operation
55
y=sin(x);
plot(x,y)
figure windows
Plot
Edit
Axes Properties Property Editor
56
Basic Operation
Graphic
M-file
"
Potential Flow
Basic Operation
q
2
57
U
q flow rate source source strength
2
r=
u sin
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
parameter
n =
k
m
c
2 km
d = n 1 2
natural frequency ,
damping ratio
damping frequency
Basic Operation
59
A0
A0 =
f0
(n2 ) + (2n )
2 2
f0
n2
(1 r 2 ) 2 + (2r ) 2
Phase angle
= tan 1
2r
1 r2
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
6
0.1
0.25
0.707
1.0
0.5
1.5
Frequency Ratio
2.5
4
0.1
0.25
0.707
1.0
3
2
1
0
Basic Operation
0.5
1.5
Frequency Ratio
2.5
61
3 MATLAB FUNCTIONS
MATLAB MATLAB
function function
sub-directories file M-file M-file
function
function function parameter
( )
function(parameter1,parameter2,...)
sine x
abs(x) absolute parameter x
sin(x)
3.1
MATLAB function
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
abs(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
arccosine inverse cosine x 1 x 1
radians 0
arctangent inverse tangent x x
2 2
acos(x)
atan(x)
atan2(x,y)
function MATLAB
1
1
1
, 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
sec( x ) =
x
arc cot( x) = arc cos
2
1+ x
hyperbolic function
e x ex
2
e x + ex
2
sinh(x)
hyperbolic sine x
cosh(x)
hyperbolic cosine x
MATLAB Function
63
tanh(x)
hyperbolic tangent x
asinh(x)
acosh(x)
atanh(x)
sinh( x )
cosh( x )
x 2 + 1
x 2 1
1+ x
1 x
x 1
x 1
cosh( x )
sinh( x )
csch( x ) =
1
sinh( x )
1
1+ x 2
acsch(x ) = ln +
x
x
x 0,
sech( x ) =
x + 1
acoth( x ) = ln
x 1
1
cosh( x )
1+ 1 x2
asech( x ) = ln
x 1
0 x 1
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)
real(z)
imag(z)
abs(z)
angle(z)
64
MATLAB Function
P = [a n , a n 1 ,... a 2 , a1 , a 0 ]
P=[1, 2, 1]
% f ( x) = x + 2 x + 1
Polyval(P,1)% f(1) 1
2
ans =
1
x=[1 2 3 4];
polyval(P,x)
ans =
4 9 16 25
n Polynomial
MATLAB Function
65
0.0000- 1.4142i
1.4142
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
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]
Q=2*P
polyval(Q,1)
ans =
8
% P( x ) = x 2 + 2 x + 1
% Q( x) = 2( x 2 + 2 x + 1) = 2 x 2 + 4 x + 2
% Q(1)
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
% P(x)*Q(x)
conv(P,Q)
ans =
2
12
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
5x 2 + 6 x 2
polynomial 5x + 15
[y,ind] = max(x)
MATLAB Function
67
max(A,B)
MATLAB matrix A B
element (i, j) aij bij
cumsum(x)
prod(x)
cumprod(x)
mean(x)
median(x)
std(x)
x vector element x
x matrix row vector column
x
x vector x element 2
element 1 2 x , element 3
element 1, 2 3 x x matrix MATLAB
column x
sum element
cumsum element
x vector element x x
matrix row vector element column
x
x vector median element x x
matrix row vector element medien
column x
x vector (standard
deviation) element x x matrix row
vector element column
x
cov(x)
corrcoef(A)
sort(x)
68
MATLAB Function
x=[4;1;6]
x =
4
1
6
y=[1 8 9]
y =
1
max(y)
ans =
9
min(A)
ans =
1
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
2
108
8
756
8
32
192
o Logical Function
MATLAB Function
69
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-aNumber, 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
find(B)
ans =
1
2
3
5
6
7
9
all(B)
ans =
1
70
MATLAB Function
finite(B)
ans =
1
1
1
1
1
1
1
1
1
MATLAB Function
71
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)
N
N element column vector
inf
file ()
[M,N]
matrix M x N column
count=fwrite(fid,a,precision)
72
MATLAB Function
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
- 16 bits.
'short'
- 32 bits.
'int'
- 32 64 bits.
'long'
'ushort'
'uint'
'ulong'
'float'
'double'
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
3.4907
4.1888
74
4.8869
5.5851
6.2832
MATLAB Function
count=fprintf(fid,format,a)
f2=fopen('c:\temp\iotest.txt','rt');
A=fscanf(f2,'%f %f',[2 5]);
B=fscanf(f2,'%f');
A
A =
0
0.5556
MATLAB Function
1.1111
1.6667
2.2222
2.7778
3.3333
3.8889
4.4444
5.0000
75
B
B =
1.0000
0.8496
0.4437
-0.0957
-0.6063
-0.9345
-0.9817
-0.7335
-0.2647
0.2837
"
Stress-Strain Curve
curve
stress-strain curve curve
stress strain
Youngs Modulus MPa
Ultimate Strength MPa
Percent Elongation at Fracture
Stress (kpsi)
0
30
55
60
68
72
74
75
76
Strain (in/in)
0
0.001
0.002
0.005
0.01
0.02
0.04
0.06
Stress (kpsi)
76
75
73
69
65
56
51
Strain (in/in)
0.08
0.10
0.12
0.14
0.16
0.18
0.19 (Fracture)
MATLAB Function
100 file 2
stress strain 2 x 100 transpose
column
Stress = A(:,1)*6.895;
Strain = A(:,2);
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
plot(Strain,Stress,'^-');
xlabel('Strain')
ylabel('Stress')
title('Stress - Strain Curve')
MATLAB Function
77
500
S tres s
400
300
200
100
0
0
78
0.02
0.04
0.06
0.08
0.1
S train
0.12
0.14
0.16
0.18
0.2
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
M-Files
79
80
M-Files
function
mypro(c)
a =
myfunc(c,d)
= tiger(d, e, f, g)
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)
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)
Pyta (3,4)
ans =
5
x= Pyta (4, 3)
x
=
5
help pyta
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
Repetitive Control Structure
If - elseif - else - end Conditional Control Structure
While loop
Repetitive Control Structure
For loop
n For Loop
m = a: b
end
MATLAB (loop) m = a
end MATLAB
for m = a + 1
m = b a b
for m = a:b:c
M-Files
l a c b
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) =
end
end
k * i ;
If
if
end
MATLAB MATLAB
end condition
84
M-Files
if
MATLAB
==
~=
MATLAB
>
>
<
<
=>
=<
AND
&
OR
x == 0
a =5
end
x = 0 a = 5 x a = 5
If-Elseif-Else
else elseif
if
1
elseif
2
elseif
4
................
else
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
end
loop MATLAB
end
a =0
while a < 5
a =a +1
b =5+a
end
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
case
2
case
3
...............
otherwise
n
end
switch MATLAB
x=input('
switch x
case 1
1-4
fprintf('
case 2
\n')
fprintf('
case 3
\n')
\n');
fprintf(' 3 \n')
case 4
M-Files
87
fprintf(' 4 \n')
otherwise
fprintf(' \n')
end
x x MATLAB x
x = 1 1
MATLAB
pause
keyboard
pause(n)
n
return
M-file M-file
88
M-Files
= 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}
{ x} = [ A]1 {b}
89
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
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
91
0
0
Ax = x
A
x
square matrix
column vector
scalar
{ d } = { 0}
{d } {0} C inverse
92
( A I ) inverse
matrix ( A I ) determinant matrix 0
A I = 0
Q T = Q 1
[B,C]=eig(A)
B =
-0.8069
-0.3437
0.5907
-0.9391
C =
-1.9282 0
0
11.9282
93
"
eigenvalue
Principal Stress Natural Frequency N-DOF
Principal Stress
zx = 75 MPa
eigenvalue eigenvector
[Direc SP]=eig(s)
Direc =
-0.4654 -0.8372 0.2872
-0.8836 0.4587 -0.0944
0.0527
0.2977
SP =
24.0644
0
0
0.9532
0
0
176.7995
0
0 -110.8640
94
Natural Frequency
x =
d 2x
dt 2
M mass matrix K
x = 2 Ae it
[ K M ]x = 0
2
[ AM ]x = 0
eigenvalue
mode shape
natural frequency mode shape
3-DOF Mass Stiffness Matrix
m1
M = 0
0
0
m2
0
0
0
m3
k1 + k 2
K = k 2
0
k2
k2 + k3
k3
0
k 3
0
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
invk =inv(k);
% D - Dynamics Matrix
D = invk*m;
% Natural Frequency
[A B]=eig(D);
B=diag(B);
A=inv(K)
D = inv(K)*M
Mode Shapes
B=sqrt(abs(1./B)); % =
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
96
-1
0.5
1.5
2.5
0.5
1.5
2.5
0.5
1.5
2.5
-1
1
0.5
eigenvalue
97
1. Interpolation MATLAB
Polynomial interpolation - 2
linear interpolation
Cubic-Spline interpolation - curve polynomial degree 3 2
slope
curve curve
98
Numerical Analysis
MATLAB
6.2 Interpolation
n Linear Interpolation
linear interpolation
MATLAB interp1
Interp1(x,y,s)
0 interp1 x MATLAB x
()
0
1
2
3
4
()
0
200
600
680
800
99
x = [0 1 2 3 4];
% x
t = 1.5 35 linear
interpolation ( x y )
s = [1.5 3.5];
y2 = interp1(x, y, s);
y2 =
400 740
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
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
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 ppform polynomial function
ppvalue
pp pp-form polynomial, s
ppval(pp,s)
spline(x, y, s)
spline(x,y,s)
ans =
421.2500 698.7500
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
5
Linear Interpolation
0
-5
0
5
Cubic Interpolation
0
-5
5
Cubic Spline Interpolation
0
-5
0
function
2- interpolation
interpolation # - MATLAB 6-
Fast Fourier Transform Interpolation Method
2- interpolation
103
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)
1.5 3.5
s=[1.5 3.5];
y1=polyval(p,s)
y1 =
412.0000 759.4286
104
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
5
Second order
0
-5
5
Third order
0
-5
5
Fourth order
0
-5
105
interpolation
Least Square Fitting
"
(1 cos )
F = mU
m U
2 (flat plat) 90
(hemispherical cup) 180
F = mU
F = 2mU
106
F mU
1 2
600 g
F L = mgl
m g L
150 mm l
F=
mgl
L
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
%
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]
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+');
%
% Polyfit
% p
p = polyfit(TheoryForce,ActualForce,1);
SlopHemi = p(1,1);
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);
SlopeFlate = p(1,1);
MaxOfx = max(TheoryForce);
MinOfx = min(TheoryForce);
xx = linspace(0,MaxOfx);
yy = polyval(p,xx);
plot(xx,yy,'r');
% Polyfit
% p
% Legend
H = [HF,HH];
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 **************
108
6
Flat Plate
Hemisphrical Cup
5
-1
0
0.5
1.5
2
2.5
Rate of Momentum Flow (N)
3.5
109
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
trapz(x,y)
integrate
x sin( x)dx
0
110
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
Parameter function
quad
111
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
112
x2 y2
dydx
integral x x 20
( script file)
x = 0:1/19:1;
for
k = 1:20
A2(i) = quad(myint2,0,1,[],[],x(i));
end
dblquad(function,inmin,inmax,outmin,outmax,tol,trace,method)
113
x2 y2
dydx
dblquad('myint3',0,1,0,1)
ans =
0.5577
MATLAB integration
function MATLAB function function function
function function integrate
MATLAB Symbolic Integration Symbolic Toolbox
0
dx
x
diff(x)
114
y ( x k ) y ( x k 1 )
x k x k 1
x = x k x k 1
function difference
dy
dx
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
dy
dx
x=1 0.3000,
dy
dx
0.3000
"
indicated
power indicator
W
V
Indicated Power
Pi =
imepV N
nr
115
V , N nr 1
2 2 4
4
( CC )
-
( bar )
-
( bar )
141.0
164.25
186.50
207.55
230.00
324.13
410.40
500.00
590.04
680.00
16.0
47.0
42.0
37.0
33.0
21.0
14.5
11.0
8.5
15.0
11.0
9.5
8.0
7.0
4.5
3.0
2.0
1.5
7.0
1.0
770.00
815.00
860.00
5.0
4.5
3.5
1.5
1.5
3.5
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
W=(trapz(V,DP))/10;
Vdis=max(V)-min(V);
imep = (W/Vdis);
Power = W*N*2*pi/(nr*60000);
%
%
%
%
N-m
Displace Volume
MPa
kW
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
25
20
15
10
5
0
100
200
300
400
500
V o lu m e , C C
600
700
800
900
117
dy
= g ( x, y )
dx
y = g ( x, y )
y(x) 1 function
(initial condition) (boundary condition)
function general solutions y(x) boundary initial
118
function a b
initial function a (initial
condition) x y y = y(x)
[x,y] = ode45(function,[a b],intial)
y = x cos x
pi],0)
119
ode23
[a b]=size(y);
y(a)
ans =
-3.1417
y() = -3.1417
ode45
[x, y] = ode45(myode,[0
[a b]=size(y);
format long
y(a)
ans =
-3.14159260200719
pi
ans =
3.14159265358979
pi],0)
y=y(x) y ( n ) =
dny
dx n
initial condition
y( x0 ) = a 0
y ( x 0 ) = a1
..........
y ( n 1) ( x 0 ) = a n 1
120
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 (1
v 2 = v1
v 22 )
v1
v 22
121
% 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')
122
1
dy
y
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
10
123
boundary
condition analytical method
boundary initial value problems Runge-Kutta numerical method
R-K
R-K solution step
boundary value problem
problem
y = x + 1 y
5
y(1) = 2, y(3) = - 1
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%)
1 3
124
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
1+
4 ( 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')
125
2
dy
y
1
-1
-2
-3
-4
1
1.2
1.4
1.6
1.8
2.2
2.4
2.6
2.8
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
G1 1
G2 2
R1 1 ( G1)
R2 2 ( G2)
D
3 G
126
G = G1 +
G 2 G1
( D R1)
R2 R1
y = x + 1
x
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);
127
R1=y(a,2);
% Second Try
G2=-5;
init=[G2 2];
[x,y]=ode45('myode4',intv,init);
[a b]=size(y);
R2=y(a,2);
while abs(y(a,2)-D)>1e-6
1E-6
G=G1+(G2-G1)*(D-R1)/(R2-R1);
init=[G 2];
1
%
G1=G2;
G2=G;
[x,y]=ode45('myode4',intv,init);
[a b]=size(y);
R1=R2;
R2=y(a,2);
loop
P=abs(y(a,2)-D);
%
fprintf('Now your error is %10.6f \n',P)
% loop
end
%
m=plot(x,y);
legend(m,'dy','y')
plot
is
is
is
is
is
is
is
is
1.207074
2.396240
0.568361
0.249510
0.045735
0.003186
0.000039
0.000000
MATLAB error
10-6 MATLAB
128
2
dy
y
1.5
1
0.5
0
-0.5
-1
-1.5
-2
-2.5
-3
1.2
1.4
1.6
1.8
2.2
2.4
2.6
2.8
"
(The Excact Solution of Boundary
Layer Theory)
(Boundary Layer)
129
Navier-Stokes Equation
2 f + ff = 0
u
= f ( )
U
U
f = df ()
d
= y
kinematic viscosity
x
y
potential flow viscous
flow Blasius Equation Boundary condition
F :
= 0 f = 0 = 0 f = 0
F :
, f = 1
130
Blasius Equation third order ordinary differential equation boundary value problem Runge
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)
0.526004
0.249148
131
Now
Now
Now
Now
your
your
your
your
error
error
error
error
0.037440
0.002332
0.000023
0.000000
is
is
is
is
4.5
d2y
dy
y
4
3.5
3
2.5
2
1.5
1
0.5
0
99%
= y @ u = 0.99U
u
= f ( )
U
f = 0.99
error
error
error
error
error
error
is
is
is
is
is
is
0.514670
0.238315
0.033354
0.001918
0.000016
0.000000
ODE MATLAB
a=y(:,2);
b=interp1(a,x,0.991,'spline')
b =
4.9654
132
= 4.9654
U
x
Ux
=
Reynolds Number, Re x = Ux
4.965x
Re x
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)
errorbar(x,y,l,u)
x = linspace (0,15,40);
y = exp(cos(x)) ;
delta = 0.1*y ;
errorbar (x,y, delta)
134
MATLAB Graphics
2.5
1.5
0.5
0
-2
10
12
14
16
o Graph Function
function file plot function Function
MATLAB fplot
fplot (function, lim, str, tot)
lim = [1 0];
fplot(exp(x),lim)
MATLAB Graphics
135
2.5
x 10
1.5
0.5
10
p Polar Plot
polar(q,r)
theta = linspace(0,2*pi,200);
r = sqrt(abs(sin(theta)).*abs(cos(theta)));
polar(theta,r)
option string ,
plot
90
0.8
60
120
0.6
0.4
150
30
0.2
180
210
330
240
300
270
136
MATLAB Graphics
feather(Z,str)
feather(x,y)
compass(z,str)
compass(x, y)
rose(v,n)
compass (x+y*i) i = 1
argument histogram frequency arguments vector v
n option MATLAB
n = 36
2.0000+1.0000i
4.0000-2.0000i
0+1.0000i
2.0000
0+4.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
-2
-4
1
150
compass
90 5
120
60
2.5
180
30
330
240
270
300
120
210
10
rose
90 4
60
150
15
30
180
210
330
240
270
300
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(x,z)
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
3
4
2
2
1
0
0
0
Stem Graph
10
15
20
15
20
Stairs Graph
6
5
4
3
2
0
MATLAB Graphics
10
15
20
10
139
s Comet Plot
Comet plot Plot
plot
comet(x,y)
pie(x)
pie(x,y)
pie(x,condition)
vector x y
vector x
element
element vector x
vector x
element x vector y x
0 1 element y 1 element
x
condition
140
MATLAB Graphics
20%
20%
Jan
Feb
Mar
Apl
May
16%
26%
18%
9.2 3
MATLAB 3
MATLAB 3
(mesh) 3
plot 3 MATLAB
n Plot 3
MATLAB Graphics
141
x
y
z
=
=
=
plot3(x,y,z)
xlabel('X')
ylabel('Y')
zlabel('Z')
title(' 3-D Plot')
3-D Plot
0.5
-0.5
8
6
8
6
4
4
2
Y
2
0
o 3
3
z = f (x,y)
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
1
2
v =
4
4
5
5
zij
3
3
4
5
= f (xij,yij)
MATLAB Graphics
143
mesh(X,Y,Z,C)
mesh(x,y,Z,C)
mesh(Z)
meshc(...)
meshz(...)
waterfall(...)
hidden on
hidden off
hidden
mesh function
x y 0 2
script file
% x vector 1 x 100
% y vector 1 x 100
% z [100 x 1] x [1 x 100] = [100 x 1]
x = linspace(0,2*pi,40);
y = x;
z = sin(x)*cos(y);
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')
off
mesh
MATLAB
mesh
surf(X,Y,Z,C)
MATLAB Graphics
parameter X, Y, Z C matrix m x n
plot (xij, yij, zij) cij
C C = Z x y vector
plot (xi , yi , zij )
145
surfc(x,y,z,c)
surfl(x,y,z,ls)
surfnorm(x,y,z)
surf(...)
vector ls = [ u h ] u (x,y) x
h (x,y)
[Nx,Ny,Nz] = surfnorm(x,y,z)
shading faceted
shading flat
shading interp
MATLAB
mesh
faceted mesh
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
3
view
view(az,el)
view(x,y,z)
view(2)
view(3)
[a,b]= view
azimuth, az elevation, el
azimuth (x,y) x
elevation (x,y)
az el
x, y, z Cartesian
MATLAB x, y, z
vector
2 (az = 0, el = 0)
3 (az = -37.50, el = 30)
a az b el
MATLAB Graphics
147
s Contour Line
contour line
contour
contour line
contour(Z)
contour(Z,n)
contour(x,y,z)
contour(...,str)
C = contour(...)
contourf(...)
clabel(C)
contour3(...)
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
0.8
35
-0.2
30
-0.8
-0.4
25 -0.6
0.6
-0.8
-0.6
0.2
0
-0.2
20
0.2
-0.4
0.6
15
0.4
0.6
0
-0.6
-0.8
10
0.8
0.4 0.2
10
15
20
25
30
35
40
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
bar3(y,Z)
MATLAB Graphics
149
stem 3
Stem3(z)
Stem3(x,y,z)
Stem3(...,'filled')
Stem3(...,linespec)
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
This is z
150
100
50
0
20
15
10
8
10
6
5
This is y
4
0
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
hot
cool
bone
copper
flag
pink
prism
jet
white
lines
colorcube
summer
autumn
winter
spring
---
-
- X - ray
- -
-
hsv color map
Color Map
color-cube
colormap ( map)
152
MATLAB Graphics
9.4
MATLAB function
153
frame
M MATLAB frame
column Matrix M n frame
M = moviein(n)
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
plot
ZORO(:,j) = getframe
end
movie(ZORO)
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
= Ur
a2
sin +
ln( r )
2
r
a, K U
M-file a =2
=K
2aU
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])
q
2ay
tan 1 2
2
x + y2 a 2
potential flow Vx =
Vy =
x
y
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');
axis equal
hold on
grid off
phi0=[-0.01 0 0.01];
% stream line
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);
v=-v;
u=abs(u);
quiver(x,y,u,v,0.6)
hold off
axis off
% velocity
% velocity vector
Response Surface
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
x)
=
function sin(x) sin(x) d sin(
dx
cos(x)
t = x^2+5*x-4
Symbolic Mathematics
( i j ) x x MATLAB
2 () MATLAB x
( x ) independent variable MATLAB
expression independent variable function symvar
symvar(exp(x))
variable
symbolic variable / symbolic expression MATLAB
symbolic variable sym
S=sym(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'
Symbolic Mathematics
161
findsym
findsym(S)
s=sym('exp(bc)*sin(z)');
findsym(s)
ans =
bc, z
x=sym('x');
class(x)
ans =
sym
f=5*x^2-3*x-1;
class(f)
ans =
sym
ezplot plot
1. plot 2
162
Symbolic Mathematics
ezplot(s)
p Expression
collect(s)
collect(s,v)
expand(s)
factor(s)
simple(s)
simplify(s)
expression S
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)
symmul(s1,s2)
sympow(s1,s2)
symsub(s1,s2)
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
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
[x y z]=solve(s1,s2,s3)
x =
9/2
y =
2
z =
-3/2
Symbolic Mathematics
165
x symbolic variable
double
x expression
double(x)
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
y' =
dy
= g( x, y)
dx
ODE
symbolic
equation option condition initial
condition independent variable MATLAB
symbolic t dy MATLAB Dy D
dt
differential dependent variable
dz
MATLAB
= sin x
dt
Dz=sin(x)
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)
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
dx
= y
initial condition
dy
5
dx
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)
diff(s,t)
diff(s,n)
n
diff(s,t,n)
differentiation expression s t n
168
int(s)
int(s)
int(s,a,b)
int(s,t,a,b)
integrate expressions t a b
int(s,m,n)
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
n Laplace Transform
Laplace Transform function f(t) time domain function L(s) s-domain
transformation
L ( s) =
f (t )e
st
dt
L = laplace(F,var1,var2)
Symbolic Mathematics
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
f (t) =
F ( ) e
jt
dt
Symbolic Mathematics
171
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)
for t a
K ( t a) dt = K
for t = a
f ( n) z
n=0
Symbolic Mathematics
F=ztrans(f,var1,var2)
f=iztran(F,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)
Symbolic Mathematics
173
174
Symbolic Mathematics
2 function 1
function f(x) f(x)
2 4
1 f(x)
f(x)
df/dx
int f
simple f
num f
den f
1/f
finv
f(x)
f(x)
f(x) ()
f(x) f(x)
f(x) f(x)
f(x) 1/f(x)
f(x) inverse function
f +a
f -a
f *a
f / a
f^a
f(x+a)
f(x*a)
Symbolic Mathematics
f(x) f(x) + a
f(x) f(x) - a
f(x) f(x) * a
f(x) f(x) / a
f(x) f(x) ^ a
f(x) f(x + a)
f(x) f(x * a)
175
f +g
f g
f *g
f /g
f(g)
g =f
swap
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
.. 1997 version
symbolic toolbox
help
Calculus.
diff
int
limit
taylor
jacobian
symsum
Differentiate.
Integrate.
Limit.
Taylor series.
Jacobian matrix.
Summation of series.
Linear Algebra.
diag
triu
tril
inv
det
rank
rref
null
colspace
eig
svd
jordan
poly
expm
Simplification.
Symbolic Mathematics
177
simplify
expand
factor
collect
simple
numden
horner
subexpr
subs
Simplify.
Expand.
Factor.
Collect.
Search for shortest form.
Numerator and denominator.
Nested polynomial representation.
Rewrite in terms of subexpressions.
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
poly2sym
sym2poly
char
Basic Operations.
178
Symbolic Mathematics
sym
syms
findsym
pretty
latex
ccode
fortran
Special Functions.
sinint
cosint
zeta
lambertw
Sine integral.
Cosine integral.
Riemann zeta function.
Lambert W function.
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)
180
M-book
11.2
Word MATLAB M-book Word
Word template Normal.dot document file Mbook
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
prompt MATLAB
notebook
M-book
181
input cell
input cell
MATLAB command window
text
Highlight
Notebook Menu Define Input Cell Alt-D
182
M-book
input cell
normal text
A=10;
B=20;
C=A*B
highlight input cell
A=10;
B=20;
C=A*B
o input cell
p AutoInit Cell
M-book
183
184
M-book
M-book
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
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
186
M-book
Alt +D
3
4
Alt + U
5
6
7
Alt + p
Alt + G
9
10
Toggle Graph
Output to Cell
Evaluate Cell
Ctrl - Enter
11
Atl - Enter
M-book
Alt + [
187
12
13
Evaluate M-book
Evaluate loop
Alt - R
Alt - L
14
Bring MATLAB to
Front
Alt - M
15
Notebook Options..
Font
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
188
M-book
2. Style Window
3. window (style)
4. style highlight style
5. Click Modify Menu bar
6. Fonts...
7. Fonts window ,
M-book
189
12 Handle Graphic
MATLAB
(Low Level Command)
(Graphical User Interface,
GUI) MATLAB
MATLAB
MATLAB
MATLAB
Figure window MATLAB Axes
Handle
handle
190
Handle Graphic
Root object
MATLAB
Figure object
Axes object
Image object
Light object.
Line object
patch object
Rectangle
Patches Surfaces
Surface object
text object
uicontextmenu object
uicontrol object
uimenu object
Context menu
MATLAB GUI
Menu bar Figure window.
object MATLAB
Handle Graphic
191
Object MATLAB
Root
Figure
Uimenu
Image
Uicontextmenu
Light
Line
Axes
Patch
Uicontrol
Rectangle
Surface
Text
MATLAB
Handle MATLAB Handle
192
Handle Graphic
(Handle)
MATLAB Object Object
Handle Object
Object Handle
(Property)
Object Description
Figure object
Axes object
Uicontrol object
Uimenu object
Uicontextmenu object
Image object
Light object
Line object
Patch object
Rectangle object
Surface object
Text object
Handle Graphic
193
h = function('property name', property value,...)
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
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
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
196
MATLAB callback (
object )
Handle Graphic
ButtonDownFcn
Children
Clipping
children
axes
CreateFcn
DeleteFcn
HandleVisibility
handle
Interruptible
Parent
Parent
Selected
SelectionHighlight
Tag
Type
UserData
Visible
MATLAB
LineStyle XMinorTickMode
MATLAB
2 3
M-files
MATLAB version
2 3
Handle Graphic
197
GET SET
GET
Graphic object
get(object_handle)
returned_value = get(object_handle,'PropertyName');
198
Handle Graphic
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
handle
handle
gcf (Get Current Figure)
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
0
Handle Graphic
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
l_color
[0 0 1] RGB
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
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
PropertyName
NewPropertyValue
20
2
handle
NewPropertyValue
Handle Graphic
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)
field a field
a.GridLineStyle
ans =
'-'
'--'
':'
'-.'
'none'
Handle Graphic
a.gridlinestyle
??? Reference to non-existent field 'gridlinestyle'.
MATLAB
MATLAB MATLAB
get factory-defined
a = get(0,'Factory');
SelectionHighlight uimenu on
Get(0,'FactoryObjectTypePropertyName')
get(0,'FactoryTextFontName')
Windows
ans =
Helvetica
Helvetica
Handle Graphic
h = findobj
205
h = findobj('PropertyName',PropertyValue,...)
h = findobj(objhandles,...)
h = findobj(objhandles,'flat','PropertyName',PropertyValue,...)
findobj handles
h = findobj
handle PropertyName
PropertyValue
findobj handle
h = findobj(objhandles,...)
handles
h = findobj(objhandles,'flat','PropertyName',PropertyValue,...)
findobj('Color','r')
20
6
Handle Graphic
new_handle = copyobj(h, p)
Parent handle parent
line
axes
copyobj
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 windows
% figure
figure %
axes
Handle Graphic
207
new_handle = copyobj(h,gca);
colormap hot
view(3)
grid on
surface colormap figure view grid
axes surface
gca
get(gcf,'CurrentAxes')
MATLAB
current axes MATLAB
plot, text, surf
current axes current figure current axes
gcbo
handle callback
h = gcbo
[h, figure] = gcbo
20
8
Handle Graphic
gco
= gco(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.
2.
3.
4.
5.
Figure Object
Axes Object
Uicontrol Object
Uimenu Object
UiContextMenu Object
Object Property
211
13.1 Figure
figure('PropertyName', PropertyValue,...)
MATLAB
figure(h)
handle h h handle
handle h h
MATLAB handle h
handle h h error
handle
MATLAB handle
MATLAB
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
Position
Units
Property Value
:
[left, bottom, width, height]
:
: inches, centimeters,
normalized, points, pixels,
characters
: pixels
Color
MenuBar
Name
NumberTitle
Object Property
: ColorSpec
: color
scheme
: none, figure
: figure
: string
: ' ' (string )
: on, off
213
Property Name
Resize
SelectionHighlight
Visible
WindowStyle
Property Description
Property Value
Figure No. n, n : on
: on, off
: on
: on, off
: on
: on, off
: on
: normal, modal
: normal
Dithermap
DithermapMode
FixedColors
MinColormap
ShareColors
: m x 3
RGB
: jet colormap
Colormap truecolor : m x 3
data
RGB
pseudocolor
: colormap
MATLABdithermap
: auto, manual
: manual
colormap
: m x 3
RGB read only
: scalar
: 64
MATLAB color table on, off
slots
: on
214
: on, off
: on
: on, off
: off
: painters, zbuffer,
OpenGL
:
MATLAB
Object Property
Property Name
Property Description
Property Value
Selected
Tag
Type
UserData
RendererMode
uicontextmenu
root object Value: always 0
parent
: on, off
: on
: string
: string
(read only)
: string 'figure'
:
: [ ] ()
: auto, manual
: auto
: handle axes
CurrentCharacter
CurrentObject
Handle
CurrentPoint
SelectionType
(read only)
: 2-element
[x-coord, y-coord]
BusyAction
: normal, extended,
alt, open
: cancel, queue
: queue
ButtonDownFcn
: string
: string
CloseRequestFcn
: string
close : string
Object Property
215
Property Name
Property Description
CreateFcn
DeleteFcn
Interruptible
KeyPressFcn
ResizeFcn
UIContextMenu
WindowButtonDownFcn
WindowButtonMotionFcn
WindowButtonUpFcn
Property Value
: string
: string
: string
: string
: on, off
: on ()
: string
: string
: string
: string
context menu
: handle Uicontrextmenu
: string
: string
: string
: string
: string
: string
: on
: on, off
( : on
CurrentObject )
HandleVisibility
HitTest
NextPlot
Pointer
216
: add, replace,
replacechildren
: add
: crosshair, arrow,
watch, topl, topr, botl, botr,
circle, cross, fleur, left,
right, top, bottom,
Object Property
Property Name
PointerShapeCData
PointerShapeHotSpot
Property Description
Property Value
fullcrosshair, ibeam,
custom
: arrow
: 16-by-16 matrix
: Pointer
custom
active spot : 2-element
[row, column]
: [1,1]
InvertHardcopy
: on, off
: on
: portrait, landscape
: portrait
: 4-element
[left, bottom, width, height]
PaperOrientation
PaperPosition
PaperPositionMode
PaperSize
: [width, height]
PaperUnits
PaperType
read only
: see property
description
: usletter
: normalized, inches,
PaperSize centimeters, points
PaperPosition
: inches
PaperType
PaperUnits
set get
Object Property
217
13.2 Axes
figure
axes
axes('PropertyName',PropertyValue,...)
axes(h)
h = axes(...)
axes object
Property Name
Property Description
GridLineStyle
Layer
LineStyleOrder
LineWidth
SelectionHighlight
TickDir
TickDirMode
218
Property Value
: on, off
: off
axes axes
(clip) figure
grid
: -, --, :, -., none
: :()
: bottom, top
: bottom
: LineSpec
: - ()
points (1 point = : points
1/72")
: 0.5 points
axes on
: on, off
: on
(tick marks)
: in, out
: in(2-D),out(3-D)
MATLAB : auto, manual
Object Property
Property Name
Property Description
Property Value
TickLength
: auto
: [2-D 3-D]
: [0.01 0.025]
two-element vector
Visible
: on, off
: on
grid : on, off
: off
surfaces text
: handles
: 2x3
HitTest
: on
Parent
Handle figure
Position
Selected
Tag
Type
Units
UserData
: figure
handle
figure
: [left bottom width
Height]
: [0.1300 0.1100
0.7750 0.8150]
: on, off
: on
: any string
: '' ( string )
: string 'axes'
: inches, centimeters,
'Position'
Characters, normalized,
Points, pixels
: Normalized
: any matrix
: [ ] ()
FontAngle
Object Property
Property Name
FontName
FontSize
FontUnits
FontWeight
Title
XLabel,
YLabel,
ZLabel
XTickLabel,
YtickLabel,
ZtickLabel
XTickLabelMode,
YTickLabelMode,
ZtickLabelMode
Property Description
Property Value
: normal
Helvetica :
Courier
: Helvetica
:
: 10
: points, normalized,
FontSize
inches, centimeters, pixels
: points
:
MATLAB
MATLAB : auto, manual
tick mark labels
: auto
220
: top, bottom
: bottom
y
: right left
: left
: normal, reverse
: normal
: [min max]
:
MATLAB
Object Property
Property Name
Property Description
XlimMode,
YlimMode,
ZlimMode
XScale,
YScale,
Zscale
: auto
XTick,
YTick,
Ztick
XTickMode,
YTickMode,
ZtickMode
Property Value
: linear (
plot
log )
ticks marks
:
tick
marks
:
MATLAB
MATLAB : auto, manual
tick mark
: auto
CameraPosition
CameraPositionMode
CameraTarget
CameraTargetMode
CameraUpVector
CameraUpVectorMode
CameraViewAngle
Object Property
: [x,y,z]
:
MATLAB
MATLAB : auto, manual
: auto
: [x,y,z]
:
MATLAB
MATLAB : auto, manual
: auto
: [x, y, z]
:
MATLAB
MATLAB : auto, manual
: auto
: 0180
221
Property Name
CameraViewAngleMode
Projection
Property Description
Property Value
:
MATLAB
MATLAB : auto, manual
: auto
projection
: orthographic,
perspective
: orthographic
DataAspectRatio
:
[dx dy dz]
:
MATLAB
DataAspectRatioMode
MATLAB : auto, manual
: auto
PlotBoxAspectRatio
:
[dx dy dz]
:
MATLAB
PlotBoxAspectRatioMode MATLAB : auto, manual
: auto
BusyAction
ButtonDownFcn
CreateFcn
DeleteFcn
Interruptible
UIContextMenu
: cancel, queue
: queue
: string
: string
: string
: string
: string
: String
: on, off
: on
contextmenu
: handle
Uicontextmenu
222
: normal, fast
: normal
Object Property
Property Name
Property Description
HandleVisibility
NextPlot
AmbientLightColor
CLim
Colormap
CLimMode
MATLAB Clim
Color
ColorOrder
XColor,
YColor,
ZColor
tick marks
Property Value
: auto, manual
: auto
: none, ColorSpec
: none
: m x 3
RGB
:
: ColorSpec
:
1.
M-file
Object Property
223
m-file
2. X Y
Y
X X
224
Object Property
Y x
XAxisLocation YAxisLocation X
Y 2
XaxisLocation and YAxisLocation
X Y
2
x-y
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.5
1.5
2.5
0.8
3
1.4
1.2
0.6
1
0.4
0.2
0.8
0.6
-0.2
0.4
-0.4
0.2
-0.6
-0.8
10
15
20
25
0
30
grid grid on
grid
grid
grid grid grid
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.5
1.5
2.5
3
1.4
0.7429
1.2
0.4857
0.2286
0.8
-0.0286
0.6
-0.2857
0.4
-0.5429
0.2
-0.8
0
10
15
20
25
0
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
1.1
0.5
1.5
2.5
3
1.4
0.8
1.2
0.5
0.2
0.8
-0.1
0.6
-0.4
0.4
-0.7
0.2
-1
10
15
20
25
0
30
228
Object Property
X2 value
0.5
1.5
2.5
3
1.4
0.8
1.2
0.5
0.2
0.8
-0.1
0.6
-0.4
0.4
-0.7
0.2
-1
10
15
X1 value
20
25
Y2 value
Y1 value
1.1
0
30
13.3 Uicontrol
user interface control object
handle = uicontrol(parent)
handle = uicontrol(...,'PropertyName',PropertyValue,...)
Object Property
Check boxes
Editable text
Frames
List boxes
Pop-up menus
Push buttons
229
7.
8.
9.
10.
Radio buttons
Sliders
Static text
Toggle buttons
GUI
uicontrol
uicontrol
1. Check boxes
check box
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
Value MATLAB
callback list box
Value
Object Property
231
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
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
Visible
: ColorSpec
:
Truecolor image control : matrix
: ColorSpec
: [0 0 0]
: on, off
: on
Uicontrol : string
list
box pop-up menu
: on, off
Uicontrol
: on
233
Property Name
Property Description
Children
Uicontrol objects
children
uicontrol
(Enable disable)
parent Uicontrol
Enable
Parent
Selected
SliderStep
Style
Tag
TooltipString
Type
UserData
Controlling the Object Position
Position
Property Value
: string
tooltip : string
object
graphics object
: string (read-only)
: uicontrol
User-specified data (
: matrix
)
: [ ]
uicontrol
: position rectangle
: [20 20 60 20]
: pixels, normalized,
inches, centimeters,
points, characters
: pixels
FontName
Font family ()
FontSize
: normal, italic,
oblique
: normal
: string
:
: size in FontUnits
Units
234
Object Property
Property Name
Property Description
FontUnits
FontWeight
HorizontalAlignment
VerticalAlignment
String
Uicontrol
list
box pop-up menu
Min
Value
:
: points, normalized,
inches, centimeters,
pixels
: points
: light, normal, demi,
bold
: normal
: left, center, right
: uicontrol object
: string
: cancel, queue
: queue
: string
callback
: string
Callback
Callback
Mode
Callback
Uicontextmenu
UIContextMenu
Information About the Current State
ListboxTop
Max
Property Value
List box
uicontrol
uicontrol
uicontrol
: string
: string
: on, off
: on
: handle
: scalar
: [1]
: scalar
:
: scalar
:
: scalar or vector
:
235
Property Name
Property Description
Property Value
HandleVisibility
handle
command line
GUIs
HitTest
: on, off
: on
push button
h = uicontrol('Style', 'pushbutton', 'String', 'Clear',...
'Position', [20 150 100 70], 'Callback', 'cla');
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,...)
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
Checked
ForegroundColor
Label
SelectionHighlight
Menu
Separator
Separator line
mode
Uimenu
Visible
handle parent
Uimenu
graphics object
uimenu
Property Value
: on, off
: off
: ColorSpec
: [0 0 0]
: string
: on, off
: on
: on, off
: off
: on, off
: on
: character
: vector of handles
: on, off
: on
: handle
: string
: string (read-only)
: uimenu
: matrix
: scalar
: [1]
Object Property
Property Name
Property Description
Property Value
BusyAction
Callback
callback
Callback
Callback
Callback
: cancel, queue
: queue
: string
handle
command line
GUIs
ButtonDownFcn
Callback
CreateFcn
DeleteFcn
Interruptible
Controlling Access to Objects
HandleVisibility
HitTest
: string
: string
: string
: on, off
: on
: on, off
: on
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,...);
Property Name
Property Description
uicontextmenu
Visible on
uicontextmenu
parent Uicontextmenu
graphics object
Property Value
: on, off
: off
: two-element vector
: [0 0]
: matrix
: scalar figure handle
: string
: string (read-only)
: uicontrol
: matrix
UserData
Controlling Callback Routine Execution
BusyAction
Callback : cancel, queue
240
: queue
Object Property
Property Name
Property Description
Property Value
Callback
Callback
Callback
Callback
: string
CreateFcn
DeleteFcn
Interruptible
Controlling Access to Objects
HandleVisibility
: string
: string
: on, off
: on
handle
: on, callback, off
: on
command line
GUIs
% context menu
hline = plot(1:10,'UIContextMenu',cmenu);
% 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
children Axes
MATLAB
242
Object Property
14 GUIDE
Graphical User Interface (GUI) user interface graphical object
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
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
Tool Application Options
Introduction to GUIDE
245
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
handle
Integer Handle off MATLAB handle
(68.0001224)
GUI handle
GUI
Introduction to GUIDE
247
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
n
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
Mygui
Pushbutton1
gcbo
[ ]
guidata(gcbo)
FIG-file GUI
Callback- callback sub funcion
handle push button
eventdata
handles structure figure GUI
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)
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);
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)
Introduction to GUIDE
251
Layout Editor
uicontrol axes
1. uicontrol axes GUI component palette
2. GUI cursor
252
Introduction to GUIDE
3.
Layout Editor
context menu
context menu subfunction application M-file
callback routine
Context figure
Introduction to GUIDE
253
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
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
Mixed
Introduction to GUIDE
257
OBJECT BROWSER
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 Property
Lable (), Tag () Seperator () Checked
Menu property () Callback menu
Introduction to GUIDE
259
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
handle
[]
guidata (gcbo) handles GUI
gcbo
260
Introduction to GUIDE
Context Menu
Menu Editor context menu
1.
2.
3.
4.
5.
6.
Introduction to GUIDE
261
Default Tag
checkbox1, checkbox2,..
edittext1, ..
frame1, ..
listbox1, .
pushbutton1,
radiobutton1,
slider1,
text1,
Togglebottom1,
Introduction to GUIDE
Callback
Application M-file
Application M-file
n Automatic Naming of Callback Routines
GUIDE Callback subfunction
[ ]
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
my_gui
Introduction to GUIDE
263
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
Command Window
Callback Subfuction
264
Application M file
Introduction to GUIDE
GUI
Switchyard Code
GUIDE
if nargin
fig
% Use
== 0 % LAUNCH
GUI
= openfig(mfilename,'reuse');
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate
code
Introduction to GUIDE
265
if
Command line GUI 0
MATLAB GUI GUI