Professional Documents
Culture Documents
第二章 常用函式..................................................6
2.1 矩陣產生函式..........................................................6
2.2 基本陣列資料函式......................................................6
2.3 矩陣運算操作函式......................................................7
2.4 特殊值與特殊矩陣......................................................7
2.5 一般數學函式..........................................................8
2.6 三角函式..............................................................8
2.7 hyperbolic 函式........................................................8
2.8 複數函式..............................................................9
2.9 多項式函式............................................................9
2.10 2D 繪圖函式...........................................................9
2.11 3D 繪圖函式..........................................................10
2.12 數值分析函式.........................................................10
2.13 邏輯函式.............................................................10
2.14 亂數函式.............................................................11
2.15 輸入與輸出函式.......................................................11
2.16 數值表現格式(format) ..................................................11
2.17 實例演練一 (chap2_1.m) ...............................................12
2.18 實例演練二 (chap2_2.m) ...............................................13
第三章 M-File 程式設計............................................14
3.1 資料型態..............................................................14
3.2 運算子................................................................14
3.3 流程控制(迴圈、判斷) ..................................................16
3.4 實例演練一 (chap3_1.m) ................................................17
3.5 實例演練二 (chap3_2.m) ................................................17
3.6 實例演練三 (chap3_3.m) ................................................18
3.7 實例演練四 (chap3_4.m) ................................................19
3.8 實例演練五 (chap3_5.m) ................................................21
第四章 矩陣與線性代數...........................................22
4.1 向量.................................................................22
4.2 向量加法與減法.......................................................22
4.3 向量範數.............................................................23
4.4 向量積...............................................................23
4.5 特徵值與特徵向量.....................................................24
4.6 單位矩陣.............................................................24
4.7 零矩陣...............................................................24
4.8 轉置矩陣.............................................................24
4.9 矩陣加法與減法.......................................................25
4.10 矩陣乘法.............................................................25
4.11 反矩陣...............................................................26
4.12 矩陣除法.............................................................26
4.13 矩陣冪次方項與指數...................................................27
4.14 矩陣 Y 的 P 階範數.....................................................27
4.15 解線性方程式.........................................................27
第六章 數值分析與統計...........................................33
6.1 多項式................................................................33
6.2 快速傅立葉轉換........................................................34
第七章 常微分方程...............................................35
7.1 一階微分方程..........................................................35
7.2 二階微分方程..........................................................35
7.3 ODE 常用函數.........................................................36
7.4 Taylor series............................................................36
7.5 Runge-Kutta Method.....................................................37
7.6 ode functions...........................................................38
7.7 First-Order Ordinary Differential Equations...................................38
7.8 Higher-Order Differential Equations.........................................41
7.9 實例演練一 (chap9_1.m) ................................................43
7.10 實例演練二 (chap9_2.m) ................................................44
7.11 實例演練三 (chap9_3.m) ................................................45
7.12 實例演練四 (chap9_4.m) ................................................46
第八章 傅立葉轉換...............................................47
8.1 傅立葉轉換與逆轉換數學方程式..........................................47
8.2 快速傅立葉轉換(FFT)常用函數...........................................47
8.3 波函式經傅立葉轉換後,觀察其純量和相位。................................48
8.4 實例演練一 (chap10_1.m) ...............................................50
第九章 常用工具箱...............................................51
9.1 符號工具箱............................................................51
9.2 地圖工具箱 ...........................................................59
第十章 類神經網路...............................................64
10.1 類神經元單元.........................................................64
10.2 類神經網路架構.......................................................67
10.3 類神經網路分類.......................................................68
10.4 範例.................................................................79
第一章 MATLAB 使用環境
1.1 視窗介面
z 命令指令視窗 command window
i. pwd, ls, cd, …
ii. who, whos, …
iii. edit, workspace, demo, …
z M-file editor:編輯檔案,如 Edit vrml.m。
z Workspace:觀看變數和變數值,使用 workspace 以呼叫視窗。
z Command history:觀看指令記錄。
z demo:觀看各種 demo。
1.2 線上說明
z help:命令指令視窗的說明,如 help sin、help min、help diff…。
z helpwin:說明輔助視窗,如 helpwin sin、helpwin min、helpwin diff…。
1.3 程式語言
z 變數:matlab 提供變數資料型態的種類,如 char、double、struct…,且在 matlab 中,
不需事先宣告變數資料型態。
z 運算子:
i. 數學運算子:.’(轉置矩陣)、.^(矩陣的次方運算)、’(共軛複數) 、.*(方陣次方)、./(右
除法)、.\(左除法)、+、_、*、/…。
ii. 關係運算子:<、<=、>、>=、==、~=。
iii. 邏輯運算子:&、|、~。
z 判斷(if、else、elseif)
i. if (a>=0)
a=a;
else a=a*(-1);
……………………………………………………………………………………
z 迴圈(for、while)
i. for index = start : increment : end
end
……………………………………………………………………………………
z 函數(function)
z 函式庫(如 sin(o)、sin(pi/2)、sin(pi)…)
z 檔案的輸出與輸入(fopen、fclose)
1
1.4 數學應用
z 解線性代數
z 2D & 3D 繪圖
z 數值分析
z 統計方法
z 微分 & 積分
……………………………………………………………………………………
1.5 demo
z 在命令視窗中使用 demo,以呼叫出視窗。
z MATLAB >> Matrices >> Basic matrix operation >> RUN。
z MATLAB >> Graphics >> 2-D Plots >> RUN。
z MATLAB >> Graphics >> 3-D Plots >> RUN。
z Toolboxes >> Mapping >> Animated Satellite Orbits >> RUN。
z Toolboxes >> Mapping >> Map Projections Comparison >> RUN。
……………………………………………………………………………………
1.6 變數與矩陣
2
1.7 實例演練一 (chap1_1.m)
% File: ../ch1/ch1_2.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: Indroduce the loop and plot
g=2;
for k=1:10,g=1+1/g;end
g
t=0:0.005:1,z=exp(10*t.*(t-1)).*sin(12*pi*t);
figure(1);plot(t,z);
figure(2);hist(randn(1000,1));
3
1.9 實例演練三 (chap1_3.m)
% File: ../ch1/ch1_3.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: Random Fibonacci sequence
%Inital Condition
x=[1 2];
%Main loop
for n=2:m-1
x(n+1)=x(n)+sign(rand-0.5)*x(n-1);
end
semilogy(1:m,abs(x))
c=1.13198824
hold on
semilogy(1:m,c.^(1:m))
title('Random Fibonacci sequence')
hold off
%File: ../ch1/ch1_4.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: Collatz iteration
count=1;
while n ~= 1
if rem(n,2) == 1 %Remainder modulo 2
n=3*n+1;
else
n=n/2;
end
count=count+1;
narray(count)=n; %Store the current iterate
end
4
1.11 實例演練五 (chap1_5.m)
%File: ../ch1/ch1_5.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: Collatz interation bar graphy
for i=1:N
count=0;
n=i;
while n~= 1
if rem(n,2) == 1
n=3*n+1;
else
n=n/2;
end
count=count+1;
end
niter(i)=count;
end
%Bar graphy
bar(niter)
%Add horizontal and vertical grid lines
grid
title('Collatz iteration count','FontSize',16)
%Label of x and y label
xlabel('Starting value','FontSize',16)
ylabel('Number of interation','FontSize',16)
%File: ../ch1/ch1_6.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: Mandelbrot set
h=waitbar(0,'Computing...');
x=linspace(-2.1,0.6,301);
y=linspace(-1.1,1.1,301);
[X,Y]=meshgrid(x,y);
C=complex(X,Y);
Z_max=1e6;it_max=50;
Z=C;
for k=1:it_max
Z=Z.^2+C;
waitbar(k/it_max)
end
close(h)
contourf(x,y,abs(Z)<Z_max,1)
title('Mandelbrot Set','FontSize',16)
5
第二章 常用函式
2.1 矩陣產生函式
函式 功能
zero 產生零矩陣(zeros array)
ones 產生全部元素均為一的矩陣(ones array)
eyes 產生單位矩陣(identity matrix)
repmat 產生元素區塊重複矩陣
rand 產生均勻分佈亂數
randn 產生正規分佈亂數
linspace 產生線性空間
logspace 產生對數空間
meshgrid 產生給 3-D plots 的 X 和 Y 陣列
2.2 基本陣列資料函式
函式 功能
size 矩陣大小
length 向量長度
ndims 陣列的階數
disp 顯示陣列或文字
isempty 檢測空矩陣
isequal 檢測單位矩陣
isnumeric 檢測數值矩陣
islogical 檢測邏輯矩陣
logical 轉換數值矩陣為邏輯矩陣
6
2.3 矩陣運算操作函式
函式 功能
reshape 更改大小
diag 對角矩陣或陣列
tril 取出矩陣下三角部份
triu 取出矩陣上三角部份
fliplr 將矩陣左右對調
flipud 將矩陣上下對調
flipdim 將矩陣沿特定方向對調
rot90 將矩陣旋轉 90 度
find 找出非零元素的指標
end 最後指標
sub2ind Linear index from multiple subscripts.
ind2sub Multiple subscripts from linear index.
2.4 特殊值與特殊矩陣
函式 功能
ans Most recent answer.
eps Floating point relative accuracy.
realmax Largest positive floating point number.
realmin Smallest positive floating point number.
pi 3.1415926535897...., PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897....
i,j Imaginary unit.
inf Returns the IEEE arithmetic representation for positive infinity.
nan The IEEE arithmetic representation for Not-a-Number.
isnan True for Not-a-Number.
isinf True for infinite elements.
isfinite True for finite elements.
flops Obsolete floating point operation count.
clock Current date and time as date vector.
date Current date as date string.
7
2.5 一般數學函式
函式 功能
abs(x) The absolute value of the elements of X
sqrt(x) The square root of the elements of X.
round(x) Rounds the elements of X to the nearest integers.
fix(x) Rounds the elements of X to the nearest integers towards zero.
floor(x) Rounds the elements of X to the nearest integers towards minus infinity.
ceil(x) Rounds the elements of X to the nearest integers towards infinity.
sign(x) Signum function.
rem(x) Remainder after division.
exp(x) The exponential of the elements of X, e to the X.
log(x) The natural logarithm of the elements of X.
log10(x) The base 10 logarithm of the elements of X.
2.6 三角函式
函式 功能
sin(x) The sine of the elements of X.
cos(x) The cosine of the elements of X.
tan(x) The tangent of the elements of X.
asin(x) Inverse sine.
acos(x) Inverse cosine.
atan(x) Inverse tangent.
atan2(y,x) Four quadrant inverse tangent.
2.7 hyperbolic 函式
函式 功能
asinh(x) The inverse hyperbolic sine of the elements of X.
cosh(x) The hyperbolic cosine of the elements of X.
tanh(x) The hyperbolic tangent of the elements of X.
asinh(x) The inverse hyperbolic sine of the elements of X.
acosh(x) The inverse hyperbolic cosine of the elements of X.
atanh(x) The inverse hyperbolic tangent of the elements of X.
8
2.8 複數函式
函式 功能
conj(x) The complex conjugate of X.
real(x) The real part of X.
imag(x) Displays matrix C as an image.
abs(x) The absolute value of the elements of X.
angle(x) Returns the phase angles, in radians, of a matrix with complex elements.
polar(theta,r) Makes a plot using polar coordinates of the angle THETA, in radians, versus
the radius RHO.
2.9 多項式函式
函式 功能
polyval(a,x) Evaluate polynomial.
conv(a,b) Convolution and polynomial multiplication.
[q,r]=deconv(n,d) Deconvolution and polynomial division.
roots(a) Find polynomial roots.
poly(r) Convert roots to polynomial.
2.102D 繪圖函式
函式 功能
plot(x,y) Plots vector Y versus vector X.
semilogx(x,y) Semi-log scale plot.
semilogy(s,y) Semi-log scale plot.
loglog(x,y) Log-log scale plot.
Axis,axis(v) Control axis scaling and appearance.
subplot Create axes in tiled positions.
pause Wait for user response.
title Graph title.
xlabel, ylabel Adds text beside the X-axis and Y-axis on the current axis.
grid Adds grid lines to the current axes.
meshgrid X and Y arrays for 3-D plots.
9
2.113D 繪圖函式
函式 功能
mesh(x_pts,y_pts,z) 3-D mesh surface.
surf(x_pts,y_pts,z) 3-D colored surface.
contour(x,y,z) X and Y specify the (x,y) coordinates of the surface as for SURF.
contour(x,y,z,v) Draw LENGTH(V) contour lines at the values specified in vector V.
meshc(x_pts,y_pts,z) Combination mesh/contour plot.
2.12數值分析函式
函式 功能
max(x) The largest element in X
[y,k]=max(x) Returns the indices of the maximum values in vector I.
max(x,y) Returns an array the same size as X and Y with the largest elements taken
from X or Y.
min(x) The smallest element in X.
[y,k]=min(x) Returns the indices of the minimum values in vector I.
min(x,y) Returns an array the same size as X and Y with the smallest elements taken
from X or Y.
sum(x) The sum of the elements of X.
prod(x) The product of the elements of X.
cumsum(x) A vector containing the cumulative sum of the elements of X.
cumprod(x) A vector containing the cumulative product of the elements of X.
Mean(x) The mean value of the elements in X.
mediam(x) The median value of the elements in X.
sort(x) Sorts the elements of X in ascending order.
std(x) Returns the standard deviation.
hist(x) Bins the elements of Y into 10 equally spaced containers
hist(x,n) Returns the number of elements in each container.
2.13邏輯函式
函式 功能
any(x) True if any element of a vector is nonzero.
all(x) True if all elements of a vector are nonzero.
find(x) Find indices of nonzero elements.
isnan(x) True for Not-a-Number.
isempty(x) True for empty matrix.
10
2.14亂數函式
函式 功能
rand(n) N-by-N matrix with random entries,
rand(m,n) M-by-N matrices with random entries.
rand(‘seed’,n) Cause the MATLAB 5 generator to be used.
rand(‘seed’) Returns the current seed of the MATLAB 4 uniform generator.
randn(n) An N-by-N matrix with random entries
randn(m,n) M-by-N matrices with random entries.
2.15輸入與輸出函式
函式 功能
fprintf Write formatted data to file.
save Save workspace variables to disk.
load Load workspace variables from disk.
input Prompt for user input.
disp Displays the array, without printing the array name.
2.16數值表現格式(format)
11
2.17 實例演練一 (chap2_1.m)
ans =
% File: ../ch2/ch2_1.m
1.6180e+000
% Author: Ming-Kai Chen, 20 Oct 2002 ans =
A=eye(2);disp(A);
disp('Result:'),disp(1/7)
12
2.18 實例演練二 (chap2_2.m)
% File: ../ch2/ch2_2.m x=
% Author: Ming-Kai Chen, 20 Oct 2002 0 0 0
x=
% Prupose: Distinctive Feature and Arithmetic of 0 0 0 0 0 0
MATLAB x=
3 4
%Distinctive Feature ans =
clear; 5
ans =
x(3)=0 7
x(6)=0 m=
x=[3 4] 4
norm(x) m=
norm(x,1) 4
k=
m=max(x) 2
[m,k]=max(x) A=
A=size(5,3) 1
s=size(A) s=
[m,n]=size(A) 1 1
m=
1
%Arithmetic n=
computer 1
isieee ans =
eps PCWIN
Warning: ISIEEE is obsolete. MATLAB only runs on IEEE machines.
realmax > In C:\MATLABR12\toolbox\matlab\general\isieee.m at line 9
-2*realmax In D:\書籍資料\Matlab\ch2\ch2_2.m at line 20
1.1*realmax ans =
0/0 1
inf-inf ans =
2.2204e-016
inf-inf ans =
NaN-NaN 1.7977e+308
realmin ans =
realmin*eps -Inf
realmin*eps/2 ans =
Inf
2^10/10 Warning: Divide by zero.
2+3*4 > In D:\書籍資料\Matlab\ch2\ch2_2.m at line 25
-2-3*4 ans =
1+2/3*4 NaN
1+2/(3*4) ans =
NaN
ans =
NaN
ans =
NaN
ans =
2.2251e-308
ans =
4.9407e-324
ans =
0
ans =
1.0240e+002
ans =
14
ans =
-14
ans =
3.6667e+000
ans =
1.1667e+000
13
第三章 M-File 程式設計
3.1 資料型態:Matlab 提供有 char、double、sparse、unit8、cell、struct 等六種型態,每一種
都是陣列模式。
型態類別 範例 說明
char char ‘Luoson-1’ 字元陣列。每一個字元用 16 個位元表示。
double [1.5 2;0.01 0] 倍精準數值陣列。一般運算子、函式、陣列
函式都支援。
sparse speye(4) 倍精準數植稀疏陣列。僅適用於二維陣列,
只儲存非零元素與其向量。運算時須配合特
殊的運算函式,例如:splu、spchol。
unit8 unit(magic(3)) 無符號的八位元整數陣列。表 0~255 的整
數。目前無運算元可用,一般使用於資料儲
存或配合影像處理工具箱使用。
cell {‘Luoson’ 100 eye(2)} 密室陣列。可以包含其它不同類別的資料陣
列,適用於大型資料庫使用。
struct Cat.name=’mimi’ 結構陣列。與密室陣列一樣,可以將不同的
Cat.age=1.2 資料型態包在同一個變數名稱下,但結構陣
Cat.color=’yellow’ 列另外含有欄位名稱。
UserObject 使用者定義的資料型態。
14
關係運算子
邏輯運算子
邏輯函式
15
3.3 流程控制(迴圈、判斷)
關鍵字 功能
if, else, elseif 根據邏輯條件,來執行一群運算。
switch, case, otherwise 根據條件值,來選擇執行項目。
while 根據邏輯條件,來決定迴圈的執行次數。
for 執行一固定次數的迴圈。
while, 與 for 語法
16
3.4 實例演練一 (chap3_1.m)
17
3.6 實例演練三 (chap3_3.m)
% File: ../ch3/ch3_3.m s= s=
% Author: Ming-Kai Chen, 20 Oct 2002 1 3.81595817775351
s= 0.52359877559830 0.50000000000000
% Prupose: Flow Control: for, while, switch 1.50000000000000 0.78539816339745 0.70710678118655
s= 1.04719755119660 0.86602540378444
s=0; 1.83333333333333 xmin =
for i=1:25,s=s+1/i,end, s= 4.940656458412465e-324
s 2.08333333333333 xmin =
s= 4.940656458412465e-324
for x=[pi/6 pi/4 pi/3],disp([x,sin(x)]),end 2.28333333333333 5
s= 6
n=5;A=eye(n); 2.45000000000000 7
for j=2:n s= 8
for i=i:j-1 2.59285714285714 9
s= 10
A(i,j)=i/j; 2.71785714285714
A(j,i)=i/j; s= Enter a real number:5
end 2.82896825396825 Nonzero and finite
end s= >>
2.92896825396825
s=
x=1; 3.01987734487734
while x>0,xmin=x;x=x/2;end s=
xmin 3.10321067821068
s=
x=1; 3.18013375513376
s=
while 1 3.25156232656233
xmin=x; s=
x=x/2; 3.31822899322899
if x== 0,break,end s=
end 3.38072899322899
s=
xmin 3.43955252264076
s=
for i=1:10 3.49510807819631
if i<5, continue,end s=
disp(i) 3.54773965714368
s=
end 3.59773965714368
s=
p=2; 3.64535870476273
switch p s=
case 1 3.69081325021727
s=
y=sum(abs(x)); 3.73429151108684
case 2 s=
y=sort(x'*x); 3.77595817775351
case inf s=
y=max(abs(x)); 3.81595817775351
otherwise
error('P must be 1, 2 or inf.');
end
function y=maxentry(A)
%MAXENTRY File: ../ch3/maxentry.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: function y=maxentry(A)
% =====> Largest absolute value of matrix entries.
% MAXENTRY(A) is the maximum of the absolute values
% of the entries of A.
y=max(max(abs(A)));
function [f,fprime]=flogist(x,a)
%MAXENTRY File: ../ch3/flogist.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: [f,fprime]=flogist(x,a)
% =====> Logistic function and its derivative.
% [F,FPRIME]=FLOGIST(X,A) evaluates the logistic
% function F(X)=X.*(1-A*X) and its derivative FPRIME
% at the matrix argument X, where A is a scalar parameter
f=x.*(1-a*x);
fprime=1-2*a*x;
function [x,iter]=sqrtn(a,tol)
%MAXENTRY File: ../ch3/sqrtn.m
% Author: Ming-Kai Chen, 20 Oct 2002
% Prupose: [x,iter]=sqrtn(a,tol)
% =====> Square root of a scalar by Newton's method.
% X=SQRTN(A,TOL) computes the square root of the scalar
% A by Newtom's method (also know as Heron's method).
% A is assumed to be >=0.
% TOL is convergence tolerance (default FSP).
% [X,ITER]=SQRTN(A,TOL) returns also the number of
% interations ITER for convergence.
sqrt 2
20
3.8 實例演練五 (chap3_5.m)
21
第四章 矩陣與線性代數
4.1 向量
⎡1 ⎤ ⎡0 ⎤ ⎡0 ⎤
v
一向量 A = (a x i , a y j, a z k ) ,其中 i = ⎢0⎥ 、 ĵ = ⎢1⎥ 、 k̂ = ⎢⎢0⎥⎥ ,則 iˆ ⋅ iˆ = ˆj ⋅ ˆj = kˆ ⋅ kˆ = 1 、
ˆ ˆ ˆ ˆ ⎢ ⎥ ⎢ ⎥
⎢⎣0⎥⎦ ⎢⎣0⎥⎦ ⎢⎣1⎥⎦
iˆ ⋅ ˆj = iˆ ⋅ kˆ = ˆj ⋅ kˆ = 0 。
⎡1 ⎤
因: i ⋅ i = i ⋅ i = [1 0 0]1×3 ⋅ ⎢⎢0⎥⎥ = 1
ˆ ˆ ˆ T ˆ
⎢⎣0⎥⎦ 3×1
⎡0 ⎤
ˆi ⋅ ˆj = iˆ T ⋅ ˆj = [1 0 0] ⋅ ⎢1⎥ = 0
1×3 ⎢ ⎥
⎢⎣0⎥⎦ 3×1
4.2 向量加法與減法
v v v v v
若 A = (a x , a y , a z ), B = (bx , b y , bz ) , 則 C = A + B = (a x + bx , a y + b y , a z + bz ) 、
v v v
D = A − B = (a x − bx , a y − b y , a z − bz ) 。
22
4.3 向量範數
X
向量 X 的二階範數(2-norm)為 = (∑ x ) 2 1/ 2
i ⇒ x12 + x 22 or x12 + x 22 + ... + x n2 ,向量 X
X
的 P 階 範 數 (p-norm) 為 = (∑ x ) i
p 1/ p
⇒ x1p + x 2p or x1p + x 2p + ... + x np , 其 中 P>1 、
P=1,2,3…∞,以 norm(variable,P)函數求取。
4.4 向量積
長度大小相等的行向量或列向量相乘,有向量內積(dot‧)和向量外積(cross X)。若
B
B
A
C
A
B
B
C
= [ai ] → 1×3 , [ ]
= bj → 1×3 , = 1×3 * 1×3
'
= 1×3 * 1×3
T
⇒ 1×3 * 3×1 = 1×1 、
D
B
B
B
= = ⇒ =
' T
1×3 * 1×3 1×3 * 1×3 3×1 * 1×3 3×3 。
23
4.5 特徵值與特徵向量
A
若存在一向量 v 與一常數 λ,使得一方陣 a 滿足 v = λv ,稱 λ 為特徵值,v 為特徵
向量。
4.6 單位矩陣
4.7 零矩陣
4.8 轉置矩陣
A
[ ] [ ]
T
24
4.9 矩陣加法與減法
B
大 小 相 等 的 矩 陣 方 可 進 行 加 減 動 作 , 若 [ ]
= aij 、 [ ]
= bij 則
C
A
B
D
A
B
= + [ ] [
⇒ cij = aij + bij 、 ] = − [ ] [ ]
⇒ d ij = aij − bij 。
4.10矩陣乘法
A
C
A
B
A 的行數等於 B 的列數,若 = aij 、 [ ] [ ]
= bij 、 [ ]
= cij ,且存在 = 關係,則
⎡1 0 ⎤
A
⎡1 0 2⎤
[ ] ⎡ ⎤
cij = ⎢∑ aik bkj ⎥ 。若 = ⎢ ⎥ 、 B = ⎢⎢0 3⎥⎥ ,
⎣k ⎦ ⎣0 3 1 ⎦ ⎢⎣2 1⎥⎦
A
B
⎡c c12 ⎤ ⎡1 + 0 + 4 0 + 0 + 2⎤ ⎡5 2 ⎤
則 = = ⎢ 11 = =
c 22 ⎥⎦ ⎢⎣0 + 0 + 2 0 + 9 + 1 ⎥⎦ ⎢⎣2 10⎥⎦
2×3 3×2 2×2
⎣c 21
⎡ d11 d12 d 13 ⎤ ⎡1 + 0 0 + 0 2 + 0⎤ ⎡1 0 2⎤
B
A
25
4.11反矩陣
X
A
A
X
I
−1
若 = ,則 = ,以 inv(variable)函數求值。
4.12矩陣除法
X
A
\
B
A
X
B
X
A
B
1
−
若 = ,則以 = 或 = 求之。
− 3x + 0 y + z = 4 ⎡− 3 0 1 ⎤ ⎡ x⎤ ⎡ 4⎤
A
若 2 x + 5 y − 7 z = 5 ,令 = ⎢⎢ 2 5 − 7 ⎥⎥ 、 = ⎢⎢ y ⎥⎥ 、 = ⎢⎢5 ⎥⎥
− x + 4 y + 8z = 6 ⎢⎣ − 1 4 8 ⎥⎦ ⎢⎣ x ⎥⎦ ⎢⎣6 ⎥⎦
⎡ − 1.3717 ⎤
X
X
A
B
X
A
\
B
利用 = 或 = −
求取 X,得 = ⎢⎢ 1.3874 ⎥⎥ 。
⎢⎣− 0.1152⎥⎦
26
4.13矩陣冪次方項與指數
A
A
^ P 表矩陣A自乘P次, ^ (− P ) 表矩陣A之反矩陣A-1自乘P次(A非異矩陣),如a^(1/2),
亦可以sqrtm(A)求之。另有 .^ 表示矩陣內同一位置元素自乘,如 A.^ (1 / 2) ,亦可以sqrt(A)
求之,
4.14矩陣 Y 的 P 階範數
Y
max
P
= x P / X P
,以 norm(Y,P)求之。
x
4.15解線性方程式
若 N 為資料量個數(number of data),M 為未知的控制變數個數(number of model
parameter)。
A
X
B
X
A
\
B
(1)方陣系統(even-determined):N=M,存在維一的一組解,若 = ,則以 =
X
A
B
1
−
或 = 求之。
(2)過限定系統(over-determined):N>M,以 min error(least square)求之。下面以
t=[0 0.3 0.8 1.1 1.6 2.3],y=[0.82 0.72 0.63 0.60 0.55 0.50]為例,認為
數 值 有 y (t ) ~ c1 + c 2 e − t 的 衰 減 指 數 趨 勢 , 過 程 如 下 , 求 得 趨 勢 方 程 式 為
y (t ) ~ 0.4760 + 0.3803e − t 。
(3)限定不足系統(under-determined):N<M,以 min length(simplify model)求之。
在 MATLAB 中會找出一組構成通解的基底,而方程式的特解則由 QR 法來決定。
27
>> A=fix(15*rand(3,3)) >> t=[0 0.3 0.8 1.1 1.6 2.3]' >> c=E\y
A= t= c=
14 7 6 0
0.4760
3 13 0 0.3000
0.3413
9 11 12 0.8000
>> B=fix(15*rand(3,1)) 1.1000 >> A=fix(15*rand(3,4))
B= 1.6000 A=
6 2.3000 13 6 6 5
9 >> y=[0.82 0.72 0.63 0.60 0.55 0.50]' 11 14 13 12
11 y= 2 13 0 0
>> X=A\B 0.8200 >> B=fix(15*rand(3,1))
X= 0.7200 B=
-0.0588 0.6300 2
0.7059 0.6000 3
0.3137 0.5500 2
>> X=inv(A)*B 0.5000 >> P=A\B
X= 0.4760 P=
-0.0588 0.3413 0.0859
0.7059 >> E= [ ones( size(t) ) exp(-t) ] 0.1406
0.3137 E= 0.0067
>> C=A*X 1.0000 1.0000 0
C= 1.0000 0.7408
6.0000 1.0000 0.4493
9.0000 1.0000 0.3329
11.0000 1.0000 0.2019
1.0000 0.1003
28
第五章 2D & 3D 繪圖
5.1 2D 繪圖
clear; clear;
x=0:pi/20:2*pi; x=0:pi/20:2*pi;
plot(x,sin(x)) subplot(2,2,1);plot(x,sin(x));
subplot(2,2,2);plot(x,cos(x));
subplot(2,2,3);plot(x,x);
subplot(2,2,4);plot(x,-x);
clear;
x=0:pi/20:2*pi;
figure(1);plot(x,sin(x));
figure(2);plot(x,cos(x));
clear; clear
x=0:pi/20:2*pi; x=0:pi/20:2*pi;
plot(x,sin(x),'r+:') plot(x,sin(x),'r',x,sin(x)-1,'b');
clear; clear;
x=0:pi/20:2*pi; x=0:pi/20:2*pi;
plot(x,sin(x)) plot(x,sin(x))
title('Sin wave') title('Sin wave')
xlabel('x value')
ylabel('sin(x)')
clear; clear;
x=0:1:1000; x=0:pi/20:2*pi;
semilogx(x,x) plot(x,sin(x))
axis([0 2*pi -1.5 1.5])
29
clear; clear;
x=0:pi/20:2*pi; x=0:pi/20:2*pi;
plot(x,sin(x)); plot(x,sin(x));
axis([0 2*pi -1.5 1.5]); hold on
text(3*pi/4,sin(3*pi/4),... plot(x,sin(x)-0.1,'r--')
'\leftarrowsin(x)=.707'); grid on
text(pi,sin(pi),...
'\leftarrowsin(x)=0');
text(5*pi/4,sin(5*pi/4),...
'sin(x)=-.707\rightarrow',...
'HorizontalAlignment','right');
30
y 黃色 m 紫色 c 青色 r 紅色
g 綠色 b 藍色 w 白色 k 黑色
. 點 v 向下三角形 - 實線
0 圓 ^ 向上三角形 : 虛線
x 打叉 < 向左三角形 -. 中軸線
* 星號 > 向右三角形 ─ 斷折線
s 正方形 p 五角星形
d 菱形 h 六角星形
5.2 3D 繪圖
clear; clear;
z=peaks(50); x=0:pi/50:10*pi;
h=surf(z); plot3(sin(x),cos(x),x);
grid on;
clear; clear;
x=0:pi/50:10*pi; z=peaks(50);
plot3(sin(x),cos(x),x,... h=mesh(z);
'.','MarkerSize',15);
grid on;
clear; clear;
[x,y]=meshgrid([-4:.1:4]); z=peaks(50);
z=peaks(x,y); h=mesh(z);
plot3(x,y,z); colormap hot;
31
clear; clear;
z=peaks(50); z=peaks(50);
h=mesh(z); h=mesh(z);
light('Position',[0 0 5]); set(h,'FaceLighting','phone',...
'FaceColor','interp');
clear; clear;
[x,y]=meshgrid([-3:.2:3]); z=peaks(50);
z=peaks(x,y); mesh(z);
mesh(x,y,z); hidden off;
plot3(x,y,z,'x','MarkerSize',3);
32
第六章 數值分析與統計
6.1 多項式:Matlab 使用列向量表示一個多項式,提供 roots 指令求解, poly 指令還原方程
式,polyval 指令計算多項式的值,polyvalm 指令做多項式矩陣運算,conv 和 deconv 指
令求迴旋折積和反回旋折積,polyder 指令求多項式微分,redisidue 指令求一個分式之部
份分式分解,polyfit(x,y,n)指令求多項式的曲線揉合方程式。
4s − 8
以下[分別以p(x)=x3-2x+5、 、p(X)=X3-2X+5 多項式為例。
s + 6s + 8
2
33
6.2 快速傅立葉轉換
指令 功能
fft 離散傅立葉轉換
fft2 二維傅立葉轉換
fftn N 維傅立葉轉換
ifft 逆傅立葉轉換
ifft2 二維逆傅立葉轉換
ifftn N 維逆傅立葉轉換
abs 向量絕對值(magnitude)
angle 向量向位值(phase)
unwrap 使相位在 180 度不會產生不連續點
>> t=0:1/50:1;
>> x=sin(2*pi*20*t)+sin(2*pi*12*t);
>> y=fft(x);
>> m=abs(y);
>> p=unwrap(angle(y));
>> f=(0:length(y)-1)'*50/length(y);
>> plot(f,m),ylabel('Abs.'),grid on
>> plot(f,p*180/pi),ylabel('Phase'),grid on
34
第七章 常微分方程
7.1 一階微分方程
x
z If y ′ = f ( x, y ) with y ( x0 ) = y 0 , then y ( x) = y 0 + ∫ f ( x)dx 。
x0
x0
7.2 二階微分方程
If p( x) y ′′ + q( x) y ′ + r ( x) y = h( x) with y ( x0 ) = y 0 and y ′( x 0 ) = v 0 ,then
′
y1 ≡ y y1 ( x0 ) = y 0 y1 = y ′
h( x ) q ( x ) r ( x) h( x ) q ( x ) r ( x)
y2 ≡ y′ y 2 ( x0 ) = v0 y 2′ = − y′ − y= − y2 − y1
p ( x) p ( x) p( x) p ( x) p ( x) p ( x)
35
7.3 ODE 常用函數
Solver Problem type Type of alogorith
ode45 Nonstiff Explicit Range-Kutta pair, orders 4 and 5.
ode23 Nonstiff Explicit Range-Kutta pair, orders 2 and 3.
ode113 Nonstiff Explicit linear multistep, orders 1 and 13.
ode15s Stiff Implicit linear multistep, orders 1 and 5.
ode23s Stiff Modified Rosenbrock pair (one-step), order 2 and 3.
ode23t Mildly stiff Trapezoidal rule (implicit), orders 2 and 3.
ode23tb Stiff Implicit Runge-Kutta type algorithm, order 2 and 3.
Function Meaning
odeset Create/alter ODE OPTIONS structure.
odeget Get ODE OPTIONS parameters.
brussode Stiff problem modelling a chemical reaction (the Brusselator).
rigidode Euler equations of a rigid body without external forces.
ballode Run a demo of a bouncing ball.
orbitode Restricted three body problem.
fem1ode Stiff problem with a time-dependent mass matrix, M(t)*y' = f(t,y).
fem2ode Stiff problem with a constant mass matrix, M*y' = f(t,y).
batonode Simulate the motion of a thrown baton.
hb1dae Stiff differential-algebraic equation (DAE) from a conservation law.
amp1dae Stiff differential-algebraic equation (DAE) from electrical circuit.
36
7.5 Runge-Kutta Method
A first-order Runge-Kutta method: uses a first-order Taylor series expansion. And Euler’s
method is equivalent to a first-order Runge-Kutta method.
A second-order Runge-Kutta method: uses a second-order Taylor series expansion.
′
A first-order Runge-Kutta integration equation is the following: y b = y a + hy a . If we have
determined the value of y b , we can estimate the next value of the function f(c) using the
′
following: y c = y b + hy b . And an initial value or boundary value is need to start the
process of estimating other points of the function f(x), the Runge-Kutta methods (and
Euler’s method) are also called initial-value solutions or boundary-value solution.
A nth-order Runge-Kutta integration equation uses terms in the Taylor’s series expansion that
include the first, second, …, nth derivatives, and computes the function estimate using n
tangent-line estimates.
37
7.6 ode functions
dy
y′ = = g ( x, y )
dx
Equation 1: y ′ = g1 ( x, y ) = 3 x 2
Equation 1 Solution: y = x 3 − 7.5
% File: ../ch9/demo9_1.m
% Author: Ming-Kai Chen, 5 Dec 2002
% Prupose: ODE example
clear;
tspan = [2 7]; yzero = 0.5;
[x,num_y] = ode45(@g1,tspan,yzero);
y=x.^3-7.5;
disp([x x num_y y])
plot(x,num_y,x,y,'o'),...
title('Solution to Equation 1'),...
xlabel('x'), ylabel('y=f(x)'),grid
38
Equation 2: y ′ = g 2 ( x, y ) = −0.131 y
Equation 2 Solution: y = 4e −0.131x
% File: ../ch9/demo9_2.m
% Author: Ming-Kai Chen, 5 Dec 2002
% Prupose: ODE example
clear;
tspan = [0 5]; yzero = 4;
[x,num_y] = ode45(@g2,tspan,yzero);
y = 4*exp(-0.131*x);
disp([x x num_y y])
plot(x,num_y,x,y,'o'),...
title('Solution to Equation 2'),...
xlabel('x'), ylabel('y=f(x)'),grid
% File: ../ch9/demo9_3.m
% Author: Ming-Kai Chen, 5 Dec 2002
% Prupose: ODE example
clear;
tspan = [0 120]; yzero = 0.0022;
[x,num_y] = ode45('g3',tspan,yzero);
y = 0.022963 - 0.020763*exp(-0.0015*x);
disp([x x num_y y])
plot(x,num_y,x,y,'o'),...
title('Solution to Equation 3'),...
xlabel('x'), ylabel('y=f(x)'),grid
39
Equation 4: y ′ = g 4 ( x, y ) = 2 ⋅ x ⋅ cos 2 ( y )
Equation 4 Solution: y = tan −1 ( x 2 + 1)
% File: ../ch9/demo9_4.m
% Author: Ming-Kai Chen, 5 Dec 2002
% Prupose: ODE example
clear;
tspan = [0 2]; yzero = pi/4;
[x,num_y] = ode45('g4',tspan,yzero);
y = atan(x.*x+1);
disp([x x num_y y])
plot(x,num_y,x,y,'o'),...
title('Solution to Equation 4'),...
xlabel('x'), ylabel('y=f(x)'),grid
Equation 5: y ′ = g 5 ( x, y ) = 3 y + e 2 x
Equation 5 Solution: y = 4e 3 x − e 2 x
clear;
tspan = [0:0.1:7]; yzero = 3;
[x,num_y] = ode45('g5',tspan,yzero);
y = 4*exp(3*x)-exp(2*x);
disp([x x num_y y])
plot(x,num_y,x,y,'o'),...
title('Solution to Equation 5'),...
xlabel('x'), ylabel('y=f(x)'),grid
40
7.8 Higher-Order Differential Equations
41
Equation: y ′′ = g ( x, y, y ′) = y ′(1 − y 2 ) − y
Define: u1 = y ′ , u 2 = y
′
Thus: u1 = y ′′ = g ( x, u 2 , u1 )
′
u 2 = y ′ = u1
′
Obtain: u1 = y ′′ = u1 (1 − u 2 ) − u 2
2
--------------------------------------------------------------------------------------------------
Define: u1 = y , u 2 = y ′
′
Thus: u1 = y ′ = u 2
′
u 2 = y ′′ = y ′(1 − y 2 ) − y = u 2 (1 − u1 ) − u1
2
---------------------------------------------------------------------------------------------------
Now: initial condition of y ′(0) = 0.0 and y (0) = 0.25 。
%uprime(1) = u(1)*(1-u(2)^2)-u(2);
%uprime(2) = u(1) ;
% File: ../ch9/demo9_6.m
% Author: Ming-Kai Chen, 5 Dec 2002
% Prupose: ODE example
clear;
tspan = [0 20]; initial = [0 0.25];
[x,num_y] = ode23('eqns2',tspan,initial);
subplot(2,1,1),plot(x,num_y(:,1)),...
title('1st Derivative of y'),grid,...
subplot(2,1,2),plot(x,num_y(:,2)),...
xlabel('x'), ylabel('y'),grid
42
7.9 實例演練一 (chap9_1.m)
d
y (t ) = − y (t ) − 5e −t sin 5t , y (0) = 1 , 0 ≤ t ≤ 3 。
dt
clear;
tspan = [0 3]; yzero = 1;
[t,y] = ode45(@myf,tspan,yzero);
plot(t,y,'*--')
xlabel t, ylabel y(t)
tspan2 = 0:4;
[t2,y2] = ode45(@myf,tspan2,yzero);
disp([t2 y2])
43
7.10 實例演練二 (chap9_2.m)
d2
Equation: θ (t ) + sin θ (t ) = 0 , 0 ≤ t ≤ 10
dt 2
d
Define: y1 = θ (t ) , y 2 = θ (t )
dt
′ d
Thus: y1 = θ (t ) = y 2
dt
′ d
2
y 2 = 2 θ (t ) = − sin θ (t ) = − sin y1
dt
d d
Obtain y1 (t ) = y 2 (t ) , y 2 (t ) = − sin y1 (t )
dt dt
% File: ../ch9/ch9_2.m
% Author: Ming-Kai Chen, 16 Nov 2002
% Prupose: ODE example
clear;
tspan = [0 10];
yazero = [1;1]; ybzero = [-5;2]; yczero = [5;-2];
[ta,ya] = ode45(@pend,tspan,yazero);
[tb,yb] = ode45(@pend,tspan,ybzero);
[tc,yc] = ode45(@pend,tspan,yczero);
[y1,y2] = meshgrid(-5:.5:5,-3:.5:3);
Dy1Dt = y2; Dy2Dt = -sin(y1);
quiver(y1,y2,Dy1Dt,Dy2Dt)
hold on
plot(ya(:,1),ya(:,2),yb(:,1),yb(:,2),yc(:,1),yc(:,2))
axis equal, axis([-5 5 -3 3])
xlabel y_1(t), ylabel y_(2), hold off
44
7.11 實例演練三 (chap9_3.m)
d
y1 (t ) = − y 2 (t ) − y 3 (t )
dt
d
y 2 (t ) = y1 (t ) + ay 2 (t )
dt
d
y 3 (t ) = b + y 3 (t )( y1 (t ) − c )
dt
% File: ../ch9/ch9_3.m
% Author: Ming-Kai Chen, 16 Nov 2002
% Prupose: ODE example
clear;
tspan = [0 100];yzero = [1;1;1];
options = odeset('AbsTol',1e-7,'RelTol',1e-4)
c = 5;
[t,y] = ode45(@rossler,tspan,yzero,options,a,b,c);
subplot(222),plot3(y(:,1),y(:,2),y(:,3)),title('c=5'),grid
xlabel y_1(t), ylabel y_2(t), zlabel y_3(t)
subplot(224),plot(y(:,1),y(:,2)),title('c=5')
xlabel y_1(t), ylabel y_2(t)
45
7.12 實例演練四 (chap9_4.m)
d d
y1 (t ) = s (t )(r1 (t ) − y1 (t )) , y 2 (t ) = s (t )(r2 (t ) − y 2 (t )) ,
dt dt
2 2
⎛d ⎞ ⎛d ⎞
k ⎜ r1 (t ) ⎟ + ⎜ r2 (t ) ⎟
⎝ dt ⎠ ⎝ dt ⎠
where s (t ) =
(r1 (t ) − y1 (t ) )2 + (r2 (t ) + y 2 (t )) 2
⎡ r1 (t ) ⎤ ⎡cos t ⎤
⎢r (t )⎥ = 1 + t ⎢ sin t ⎥
⎣2 ⎦ ⎣ ⎦
k = 0.75;
r = sqrt(1+t)*[cos(t);sin(t)];
r_p= (0.5/sqrt(1+t))*[cos(t)-2*(1+t)*sin(t);sin(t)+2*(1+t)*cos(t)];
dist = norm(r-y);
if dist > 1e-4
factor = k*norm(r_p)/dist;
yprime = factor*(r-y);
else
error('ODE model ill-defined.')
end
% File: ../ch9/ch9_4.m
% Author: Ming-Kai Chen, 16 Nov 2002
% Prupose: ODE example
clear;
tspan = [0 10];yzero = [3;0];
[tfox,yfox] = ode45(@fox1,tspan,yzero);
plot(yfox(:,1),yfox(:,2)), hold on
plot(sqrt(1+tfox).*cos(tfox),sqrt(1+tfox).*sin(tfox),'--')
plot([3 1],[0 0],'o')
axis equal, axis([-3.5 3.5 -2.5 3.1])
legend('Fox','Rabbit',0), hold
offsubplot(222),plot3(y(:,1),y(:,2),y(:,3)),title('c=5'),grid
xlabel y_1(t), ylabel y_2(t), zlabel y_3(t)
subplot(224),plot(y(:,1),y(:,2)),title('c=5')
xlabel y_1(t), ylabel y_2(t)
46
第八章 傅立葉轉換
8.1 傅立葉轉換與逆轉換數學方程式
⎛ n −1 ⎞
N − j 2 Π ( k −1) ⎜ ⎟
FFT: X (k ) = ∑ x(n)e ⎝ N ⎠
,1 ≤ k ≤ N 。
n =1
⎛ n −1 ⎞
1 N − j 2 Π ( k −1) ⎜ ⎟
IFFT: X (n) =
N
∑ x(k )e
k =1
⎝ N ⎠
,1 ≤ n ≤ N 。
8.2 快速傅立葉轉換(FFT)常用函數
函數 意義
fft 離散傅立葉轉換
fft2 二維傅立葉轉換
fftn N 維傅立葉轉換
ifft 逆傅立葉轉換
ifft2 二維傅立葉轉換
iffn N 維逆傅立葉轉換
abs 向量絕對值(magnitude)
angle 向量的相位角(phase)
unwrap 使相位在 180 度不會產生不連續點
The fast Fourier transform (FFT), use fft function by y=fft(x). The inverse FFT, x = Fn * y , is
carried out by ifft function using x=ifft(t).
47
8.3 波函式經傅立葉轉換後,觀察其純量和相位。
% File: ../ch10/demo10_1.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: Gnerate a 20 Hz sinnsoid samples at 128 Hz.
clear;
N = 64;
T = 1/128;
k = 0:N-1;
x = sin(2*pi*20*k*T);
X = fft(x);
magX = abs(X);
hertz = k*(1/(N*T));
figure;
subplot(311);plot (0:T:T*(N-1),x), ylabel ('x(kT)'), grid on
subplot(312);stem (k(1:N),magX(1:N)), ylabel ('|X(k)|'), grid on
subplot(313);stem (hertz(1:N),magX(1:N)), ylabel ('|X(k)|'), grid on
% File: ../ch10/demo10_1.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: Gnerate a 20 Hz sinnsoid samples at 128 Hz.
clear;
N = 64;
T = 1/128;
k = 0:N-1;
x = sin(2*pi*19*k*T);
X = fft(x);
magX = abs(X);
hertz = k*(1/(N*T));
sum(x-ifft(fft(x)))
figure;
subplot(311);plot (0:T:T*(N-1),x), ylabel ('x(kT)'), grid on
subplot(312);stem (k(1:N/2),magX(1:N/2)), ylabel ('|X(k)|'), grid on
subplot(313);stem (hertz(1:N/2),magX(1:N/2)), ylabel ('|X(k)|'), grid
on
% File: ../ch10/demo10_3.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: FFT example
clear;
t = 0:1/50:1;
x = sin(2*pi*20*t)+sin(2*pi*12*t);
y = fft(x);
m = abs(y);
p = unwrap(angle(y));
f = (0:length(y)-1)'*50/length(y);
figure;
subplot(311);plot (t,x), ylabel ('y=fft(x)'), grid on
subplot(312);plot (f,m), ylabel ('Abs'), grid on
subplot(313);plot (f,p*180/pi), ylabel ('phase'), grid on
48
% File: ../ch10/demo10_4.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: FFT example
clear;
n=63; L=2;
t = -L: 2*L/n: L;
y = exp(13*i*pi*t/L);
z = fft(y);
p1 = angle(z);
p2 = unwrap(angle(y));
figure;
subplot(411);stem (t,y), ylabel ('y=fft(t)'), grid on
subplot(412);stem (0:n,abs(z)), ylabel ('Abs'), grid on
subplot(413);stem (0:n,p1), ylabel ('phase'), grid on
subplot(414);stem (0:n,p2), ylabel ('phase'), grid on
% File: ../ch10/demo10_5.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: FFT example
clear;
n=63; L=2;
t = -L: 2*L/n: L;
y = sin(13*pi*t/L);
z = fft(y);
p1 = angle(z);
p2 = unwrap(angle(y));
figure;
subplot(411);plot (t,y), ylabel ('y=fft(t)'), grid on
subplot(412);plot (0:n,abs(z)), ylabel ('Abs'), grid on
subplot(413);plot (0:n,p1), ylabel ('phase'), grid on
subplot(414);plot (0:n,p2), ylabel ('phase'), grid on
% File: ../ch10/demo10_6.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: FFT example
clear;
n=63; L=2;
t = -L: 2*L/n: L;
y = cos(20*pi*t/L);
z = fft(y);
p1 = angle(z);
p2 = unwrap(angle(y));
figure;
subplot(411);plot (t,y), ylabel ('y=fft(t)'), grid on
subplot(412);plot (0:n,abs(z)), ylabel ('Abs'), grid on
subplot(413);plot (0:n,p1), ylabel ('phase'), grid on
subplot(414);plot (0:n,p2), ylabel ('phase'), grid on
49
8.4 實例演練一 (chap10_1.m)
本範例所取得的資料來源為中央氣象局網站(http://www.cwb.gov.tw/V3.0/index.htm),
選取 1999/09/21,921 大地震中主震原始資料(ASCI)的草嶺站資料(CHN5,CHY080),本筆
資料相關資訊如下:
StationCode: CHY080
LocationLongitude(°E): 120.678
LocationLatitude (°N): 23.597
LocationElavation(M): 840.0
InstrumentKind: A900A(T362002.263 )
StartTime: 1999/ 9/20 17:47: 2.0
SampleRate(Hz): 200
AmplitudeUnit: gal
RecordLength(sec): 90.0
DataSequence: U(+); N(+); E(+)
Data: 3F10.3
5.323 -13.757 -15.612
% File: ../ch10/ch10_1.m
% Author: Ming-Kai Chen, 7 Dec 2002
% Prupose: FFT example
clear;
N = 18000;
T = 1/200;
k = 0:N-1;
hertz = k * (1/(N*T));
load 921_CHY080.dat;
Ux = X921_CHY080(:,1)';
UX = fft(Ux);
UP = unwrap(angle(UX));
figure(1);
subplot(311);plot (0:T:T*(N-1),Ux), ylabel ('Ux'), grid on
subplot(312);plot (hertz(1:N),abs(UX)), ylabel ('|UX(k)|'), grid on
subplot(313);plot (hertz(1:N),UP), ylabel ('phase(U)'), grid on
Nx = X921_CHY080(:,2)';
NX = fft(Nx);
NP = unwrap(angle(NX));
figure(2);
subplot(311);plot (0:T:T*(N-1),Nx), ylabel ('Nx'), grid on
subplot(312);plot (hertz(1:N),abs(NX)), ylabel ('|NX(k)|'), grid on
subplot(313);plot (hertz(1:N),NP), ylabel ('phase(N)'), grid on
Ex = X921_CHY080(:,3)';
EX = fft(Ex);
EP = unwrap(angle(EX));
figure(3);
subplot(311);plot (0:T:T*(N-1),Ex), ylabel ('Ex'), grid on
subplot(312);plot (hertz(1:N),abs(EX)), ylabel ('|EX(k)|'), grid on
subplot(313);plot (hertz(1:N),EP), ylabel ('phase(E)'), grid on
50
第九章 常用工具箱
9.1 符號工具箱
51
z 符號式變數與表示法
>> x=sym('x') >> p=expand((1+x)^4)
x= p=
x x^4+4*x^3+6*x^2+4*x+1
>> d1=sym('d1') >> horner(p)
d1 = ans =
d1 1+(4+(6+(4+x)*x)*x)*x
>> syms a b c d3 >> syms x;y=sqrt(cos(x)+i*sin(x));
>> 1/(x+1) >> simple(y)
ans = simplify:
1/(x+1) (cos(x)+i*sin(x))^(1/2)
>> syms x y radsimp:
>> d=[x+1 x^2 x-y;1/x 3*y/x 1/(1+x); 2-x x/4 3/2] (cos(x)+i*sin(x))^(1/2)
d= combine(trig):
[ x+1, x^2, x-y] (cos(x)+i*sin(x))^(1/2)
[ 1/x, 3*y/x, 1/(x+1)] factor:
[ 2-x, 1/4*x, 3/2] (cos(x)+i*sin(x))^(1/2)
>> d(2,2) expand:
ans = (cos(x)+i*sin(x))^(1/2)
3*y/x combine:
>> c=d(2,:) (cos(x)+i*sin(x))^(1/2)
c= convert(exp):
[ 1/x, 3*y/x, 1/(x+1)] exp(i*x)^(1/2)
>> e=(1+x)^4/(1+x^2)+4/(1+x^2) convert(sincos):
e= (cos(x)+i*sin(x))^(1/2)
(x+1)^4/(1+x^2)+4/(1+x^2) convert(tan):
>> pretty(e) ((1-tan(1/2*x)^2)/(1+tan(1/2*x)^2)+2*i*tan(1/2*x)/(1+
4 tan(1/2*x)^2))^(1/2)
(x + 1) 4 collect(x):
-------- + ------ (cos(x)+i*sin(x))^(1/2)
2 2 ans =
1+x 1+x exp(i*x)^(1/2)
>> simplify(e)
ans =
x^2+4*x+5
S = 1 + 2 2 + 3 2 + 4 2 + ...... + n 2
1 1 1
S = 1 + 2 + 2 + ......
2 3 42
1 1 1 1
Riemann Zeta 函數(zeta): ξ (k ) = 1 + k
+ k + k + ..... + k + ......
2 3 4 r
1 1 1 1
S = 1+ + + + + ......
1! 2! 3! 4!
1 1 1 1
S = 1+ + 2
+ 2
+ + ......
1! (2!) (3!) (4!) 2
z 符號式的解方程式 (solve)
>> syms x >> f3=x^3-7/(2*x^2)-17/(2*x)+5 >> x.^2+y.^2,x.^2-y.^2
>> f1=x^2-4*x+3 f3 = ans =
f1 = x^3-7/2/x^2-17/2/x+5 [ a]
x^2-4*x+3 >> [ a]
>> solve(f1) [x,y]=solve('x^2+y^2=a','x^2-y^2=b') [ a]
ans = x= [ a]
[ 1] [ 1/2*(2*b+2*a)^(1/2)] ans =
>> f2=x^3-7/2*x^2-17/2*x+5 [ -1/2*(2*b+2*a)^(1/2)] [ b]
f2 = [ 1/2*(2*b+2*a)^(1/2)] [ b]
x^3-7/2*x^2-17/2*x+5 [ -1/2*(2*b+2*a)^(1/2)] [ b]
>> solve(f2) y= [ b]
ans = [ 1/2*(-2*b+2*a)^(1/2)]
[ 5] [ 1/2*(-2*b+2*a)^(1/2)]
[ 1/2] [ -1/2*(-2*b+2*a)^(1/2)]
[ -2] [ -1/2*(-2*b+2*a)^(1/2)]
53
z 符號式微分(diff)
df 1 x n +1
f 1 = xn ,
dx
= nx n −1 , ∫ f 1dx =
n +1
+k
df 2
f 2 = x −1 ,
dx
= − x −2 , ∫ f 2dx = ln( x) + k
df 3
f 3 = ln( x) ,
dx
= nx n −1 , ∫ f 3dx = x ln( x) − x + k
f 4 = ea x
f 5 = e ax
f 6 = ax
f 7 = sin(ax)
f 8 = cos(ax)
x
f 9 = sin −1 ( )
a
f 10 = sinh(ax)
54
z 符號式積分 (int)
z 符號式偏微分 (diff)
>> syms u v w
>> fmv=u*v*w/(u+v+w)
fmv =
u*v*w/(u+v+w)
>> d=[diff(fmv,u) diff(fmv,v) diff(fmv,w)]
d=
[ v*w/(u+v+w)-u*v*w/(u+v+w)^2, u*w/(u+v+w)-u*v*w/(u+v+w)^2, u*v/(u+v+w)-u*v*w/(u+v+w)^2]
>> diff(d(3),u)
ans =
v/(u+v+w)-u*v/(u+v+w)^2-v*w/(u+v+w)^2+2*u*v*w/(u+v+w)^3
>> pretty(ans)
v uv vw uvw
-------- - ------------ - ------------ + 2 ------------
u+v+w 2 2 3
(u + v + w) (u + v + w) (u + v + w)
>> diff(d(2),w)
ans =
u/(u+v+w)-u*w/(u+v+w)^2-u*v/(u+v+w)^2+2*u*v*w/(u+v+w)^3
>> diff(ans,u)
ans =
1/(u+v+w)-u/(u+v+w)^2-w/(u+v+w)^2+2*u*w/(u+v+w)^3-v/(u+v+w)^2+2*u*v/(u+v+w)^3+2*v*w/(u+v+w)^3-
6*u*v*w/(u+v+w)^4
55
z 符號式解常微分方程 (dsolve)
函數 dsolve 解微分方程式的一般呼叫如下:
sol = dsolve(' de1, de2, de3,......, den, in1, in 2, in3,..., inn' )
其中參數 de1, de2, de3, ……den 代表各別微分方程,需使用符號式變數;標準的 matlab
運算元與代表一階、二階、及高階的微分運算子為 D1, D2, D3, ……Dn,以符號式表示;
初值設定條件為 in1, in2, in3, ……inn,代表微分方程的初值條件,若應變數為 y,初始條
件為 y (0) = 1, Dy(0) = 0, D 2 y (3) = 9.1,表示 t=0 時,y 值為 1, dy / dt = 0, d 2 / dt 2 = 9.1 。值
得注意的是 matlab 最大接受 12 個輸入參數。
下面舉一些微分方程為例,並執行之!
dy
(1 + t 2 ) + 2ty = cos t 。
dt
d2y
+ y = cos 2 x , y (0) = 0 。
dx 2
d4y dy
4
= y ,when x = 0 時,則 y = 0, = 1。
dt dx
>> syms t y
>> s=dsolve('(1+t^2)*Dy+2*t*y=cos(t)')
s=
(sin(t)+C1)/(1+t^2)
>> pretty(s)
sin(t) + C1
-----------
2
1+t
>> s=dsolve('(1+t^2)*Dy+2*t*y=cos(t),y(0)=0')
s=
1/(1+t^2)*sin(t)
>> pretty(s)
sin(t)
-----
2
1+t
>> dsolve('D2y+y=cos(2*x), Dy(0)=1, y(0)=0','x')
ans =
(1/6*cos(3*x)-1/2*cos(x))*cos(x)+(1/2*sin(x)+1/6*sin(3*x))*sin(x)+1/3*cos(x)+sin(x)
>> simplify(ans)
ans =
-2/3*cos(x)^2+1/3*cos(x)+sin(x)+1/3
56
dy e − x
= ,when x = 1 時,則 y = 1 。
dx x
dy
= cos(sin x) 。
dx
d 2x a dx
2
+ sin t = 0 ,when t = 0 時,則 x = 1, = 0。
dt b dt
du a
= − sin t
dt b
dx
=u
dt
57
z 符號式傅立葉轉換 (fourier,ifourier)
函數 f(x)的傅立葉轉換定義, F ( s ) = ζ [ f ( x)] = ∫
∞
f ( x)e − sx dx ,其中 s=jω(虛數),亦
−∞
即 F ( s ) = ζ [ f ( x)] = ∫
∞
f ( x)e − jωx dx ,其中 F(ω)為複數,稱 f(x)的頻譜。反傅立葉轉換定義
−∞
為 f ( x) = ζ −1 [F (ω )] =
1 ∞
∫ F (ω )e − jωx dω ,分別以 ζ、ζ 表示傅立葉轉換與反傅立葉轉
-1
2π −∞
換。
>> syms x
>> y=fourier(cos(3*x))
y=
pi*Dirac(w-3)+pi*Dirac(w+3)
>> z=ifourier(y)
z=
1/2*exp(3*i*x)+1/2*exp(-3*i*x)
>> simplify(z)
ans =
cos(3*x)
58
9.2 地圖工具箱
• 基本圖幅:一般圖形;立體圖形
• 資料的展示
基本指令
• WORLDMAP
• SCALERULER
• CONTOURCMAP
• VIEW(3)
• AXESM
• POLCMAP
• FRAMEM;GRIDM;DISPLAYM
• CONTOURM
• CLABELM
• SET
WORLDMAP : WORLDMAP maps a country or region using the WORLDLO atlas data
• WORLDMAP REGION or WORLDMAP('REGION')
• WORLDMAP('REGION','TYPE')
• WORLDMAP(latlim,lonlim)
• WORLDMAP('hi',...) or WORLDMAP('lo',...)
60
VIEW(3) 3-D graph viewpoint specification.
sets the default 3-D view, AZ = -37.5, EL = 30.
˙VIEW(AZ,EL) and VIEW([AZ,EL])
61
EX: figure
axesm('MapProjection','ortho','Origin',[-35 70 45])
framem;gridm
displaym(worldlo('POpatch'))
polcmap
hidem(gca)
CONTOURM : Project a contour plot of data onto the current map axes
•CONTOURM(lat,lon,map)
• CONTOURM(map,maplegend)
• CONTOURM(lat,lon,map,'LineSpec')
• [c,h] = CONTOURM(...)
• CONTOURM(map,maplegend,...)
• CONTOURM(lat,lon,map,'PropertyName',PropertyValue,...)
CLABELM : Add contour labels to a map contour plot.
• CLABELM(CS,H,V)
• H = CLABELM(...) returns handles to the TEXT (and possibly LINE) objects created
62
SET : Set object properties.
• SET(H,'PropertyName',PropertyValue)
• SET(H,a)
• SET(H,'PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
• A = SET(H, 'PropertyName')
63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Chapter 10 類神經網路
10.1 類神經元單元
p為輸入,w為輸入的權重(Weight)
Σ為一計算節點,表示將所有輸送到此節點的輸入加
起來。而其值即為n。
f為一整型節點,將f()稱之為激發函數或轉移函數,
功能為把n值整型成一輸出值a。
每個計算節點皆還有一權重b (Bias,偏壓)
64
其輸入值永遠為1。
n = p*w + b
當n≧0時,視為輸入激發此神經元
n<0時,視為輸入被壓抑
當b為負值時寫成
n = p*w – TH
此時稱TH為臨界值。
即 p*w 須大於等於TH
才會激發此神經元
將n帶入f()中即可得輸出值
a = f ( w*p + b ) 65
Transfer Functions
= 1/ ( 1 + exp(-n) )
66
10.2 類神經網路架構
67
10.3 類神經網路的分類
認知器(Perceptrons)
學習法則(Learning rule)
單層類神經網路(Single-layer NN)
適應線性元件(ADALINE)
多層類神經網路(Multi-layer NN)
倒傳遞類神經網路
(Back-Propagation NN)
68
認知器(Perceptrons)
學習法則(Learning rule)
偏壓為b,TF為hardlim,輸出層只有一個神
經元,沒有隱藏層,具有學習能力。
69
70
單層類神經網路(Single-layer NN)
適應線性元件(ADALINE)
與認知器唯一不同為TF換成purelin
71
72
多層類神經網路(Multi-layer NN)倒
傳遞類神經網路
(Back-Propagation NN)
此類神經網路是目前類神經網路學習模式最具
代表性,應用最普遍的模式。
其基本原理是把一組樣本的輸出入問題轉換變
成一個類似於非線性最佳化的問題,利用最陡
坡降法的觀念,將誤差最小化,目的在降低輸
出單元目標輸出值與推論輸出值之差距,其運
作過程分為學習與測試或回想兩部份
73
多層類神經網路(Multi-layer NN)倒
傳遞類神經網路
(Back-Propagation NN)
在向前傳遞的過程中,每一層神經元的狀態
只引響下一層神經元的狀態。若在輸出層不
能得到期望的輸出,則向後傳遞,將誤差訊
號沿原來的連接通路返回,修改各神經元間
的連結權重,乳此反覆直到誤差訊號最小。
通常以一次一個訓練範例來進行,所有的訓
練範例學習完稱作一個學習循環,訓練成功
的網路通常需要上百個或上千個訓練範例。
74
75
76
77
Custom Network
78
Input: p = [-π:0.02:π]
10.4 Example
w1 = [-0.8007;-0.8007];b1 = [1.1751;-1.1753];
w2 = [1.3328; -1.3324];b2 = [-1.2100]
a1 = tansig(w1*p+b1*ones(size(p)));
a = purelin(w2*a1+b2*ones(size(p)));
79
plot(p,a),grid
1
0.5
-0.5
-1
-1.5
-4 -3 -2 -1 0 1 2 3 4
一個FFNN有足夠的層次及適當的轉移函數,他
就可以近似任何線性或非線性函數。
80
References