MATLAB n For km s n Statements n
MATLAB 之 程應用:程式流程控制 n For k=m: s: n Statements n End 5
MATLAB 之 程應用:程式流程控制 練習 Summing a series with a for loop % script file: summing. m s=0; % set a variable to 0 so that 1/n^2 can be repeatedly added to it N=10000; % set the upper limit of the sum for n=1: N % add 1/n^2 to s each time, then put the answer back into s s=s+1/n^2; end fprintf(’ Sum = %g n’, s) % print the answer % calculate the sum of the squares of the reciprocals of the % integers from 1 to 10, 000 n=1: 10000; sum(1. /n. ^2) 6
MATLAB 之 程應用:程式流程控制 練習 Products with a for loop % script file: product. m P=1; % set the first term in the product N=20; % set the upper limit of the product for n=2: N P=P*n; end fprintf(’ N! = %g n’, P) % print the answer factorial(20) gamma(21) 7
MATLAB 之 程應用:程式流程控制 練習 Recursion relations with for loops %script file: recursion. m a(1)=1; % put the first element into the array N=19; % the first one is loaded, so let’s load 19 more for n=1: N a(n+1)=(2*n-1)/(2*n+1)*a(n); End format short disp(a) % display the resulting array of values format rat disp(a) format short 8
MATLAB 之 程應用:程式流程控制- for loop n n 若要跳出 for 迴圈,可用 break 指令。例如,若要找出最小 的 n 值,滿足 n! > 10100,可輸入如下: 範例 4 : break 01. m for i = 1: 1000 if prod(1: i) > 1 e 100 fprintf('%g! = %e > 1 e 100n', i, prod(1: i)); break; % 跳出 for 迴圈 end 70! = 1. 197857 e+100 > 1 e 100 11
MATLAB 之 程應用:程式流程控制- for loop n n 在一個迴圈內若要直接跳至到此迴圈下一回合的執行,可使用 continue 指令。 範例 5 : continue 01. m x = [1 -2 3 -4 5]; pos. Total = 0; for i = 1: length(x) if x(i)<0, continue; end % 若 x(i) 小於零,跳到此迴圈的下一回合 pos. Total=pos. Total+x(i); end pos. Total % 顯示 pos. Total 的值 pos. Total = 9 12
MATLAB 之 程應用:程式流程控制– while loop n n 先前產生調和數列的例子,亦可用 while 迴圈改寫如下: 範例 6 : while 01. m x = zeros(1, 6); i = 1; while i<=6 x(i) = 1/i; i = i+1; end x % 顯示 x x= 1. 0000 0. 5000 0. 3333 0. 2500 0. 2000 0. 1667 14
MATLAB 之 程應用:程式流程控制 練習 x = 5; k = 0; while x < 25 k = k + 1; y(k) = 3*x; x = 2*x-1; end x = 8; while x ~=0 x = x - 3; end 16
MATLAB 之 程應用:程式流程控制 練習 n n n n n total = 0; k = 0; while total < 1 e+4 k = k + 1; total = 5*k^2 - 2*k + total; end disp(’The number of terms is: ’) disp(k) disp(’The sum is: ’) disp(total) 17
MATLAB 之 程應用:程式流程控制 條件/分支指令 n 二種條件指令(Branching Command): n n if-then-else 條件指令 switch - case - otherwise 條件指令 18
MATLAB 之 程應用:程式流程控制 練習 %script file: logic. m clear; a=1; b=3; % If the number a is positive set c to 1; if a is 0 or negative set c to 0 if a>0 c=1 else c=0 end % if either a or b is non-negative, add them to obtain c; % otherwise multiply a and b to obtain c if a>=0 | b>=0 % either non-negative c=a+b else c=a*b % otherwise multiply them to obtain c end 22
MATLAB 之 程應用:程式流程控制 練習 n n n n x = [4, -9, 25]; if x < 0 disp(’Some elements of x are negative. ’) else y = sqrt(x) end 結果會是甚麼? 23
MATLAB 之 程應用:程式流程控制 練習 n n n n x = [4, -9, 25]; if x >= 0 y = sqrt(x) else disp(’Some elements of x are negative. ’) end 結果會是甚麼? 24
MATLAB 之 程應用:程式流程控制 elseif n if logical expression 1 n statement group 1 elseif logical expression 2 statement group 2 n else n n statement group 3 end 25
MATLAB 之 程應用:程式流程控制 練習 n n n n if x > 10 y = log(x) elseif x >= 0 y = sqrt(x) else y = exp(x) - 1 end 26
MATLAB 之 程應用:程式流程控制- if-then-else n n 若要進行更多向的條件,只需一再重覆 elseif 即可。例如,欲判斷 y 向量之元素 是屬於 3 n、3 n+1、 或 3 n+2,可輸入如下: 範例10 : if 03. m y = [3 4 5 9 2]; for i = 1: length(y) if rem(y(i), 3)==0 fprintf('y(%g)=%g is 3 n. n', i, y(i)); elseif rem(y(i), 3)==1 fprintf('y(%g)=%g is 3 n+1. n', i , y(i)); else fprintf('y(%g)=%g is 3 n+2. n', i , y(i)); end y(1)=3 is 3 n. y(2)=4 is 3 n+1. y(3)=5 is 3 n+2. y(4)=9 is 3 n. y(5)=2 is 3 n+2. 28
MATLAB 之 程應用:程式流程控制 練習 n 陣列 A中不小於 0的元素取平方根,其他元素 則加上50,求新的陣列 A =[0 -1 4; 9 -14 25; -34 49 64]; for m=1: size(A, 1) for n = 1: size(A, 2) if A(m, n)>=0 B(m, n)=sqrt(A(m, n)); else B(m, n)=A(m, n)+50; end end A =[0 -1 4; 9 -14 25; -34 49 64]; C=(A>=0); A(C)=sqrt(A(C); A(~C)=A(~C)+50; 29
MATLAB 之 程應用:程式流程控制 Implied loop 內涵迴圈 x=[0: 5: 100]; y=cos(X) 等效於 x=[-10, -5, 0, 5, 10]; 等效於 y=find(x>0) for k=1: 21 x=(k-1)*5 y(k)=cos(x); end x=[-10, -5, 0, 5, 10]; m=0; for k=1: length(x) If x(k)>0 m=m+1; y(m)=k; end 30
MATLAB 之 程應用:程式流程控制 switch-case-otherwise 指令 n n MATLAB 在第五版開始支援 switch-case-otherwise 的多向條件指令,其 使用語法如下: switch expression case value(1) statement(1) case value(2) statement(2) case value(n-1) statement(n-1) otherwise statement(n) end 在上述語法中,expression 為一數值或字串,當其值和 value(k) 相等時, MATLAB 即執行 statement(k) 並跳出 switch 指令。若 expression 不等 於 value(k),k=1, 2, …, n-1,則 MATLAB 會執行 statement(n) 並跳出 switch 指令。 31
MATLAB 之 程應用:程式流程控制 – switch case n n 欲根據月份來判斷其季別,可輸入如下: 範例11 : switch 01. m for month = 1: 12 switch month case {3, 4, 5} season = 'Spring'; case {6, 7, 8} season = 'Summer'; case {9, 10, 11} season = 'Autumn'; case {12, 1, 2} season = 'Winter'; end fprintf('Month %d ===> %s. n', month, season); end Month 1 ===> Winter. . . . Month 12 ===> Winter. 32
MATLAB 之 程應用:程式流程控制 - switch case n n 如果 expression 是字串,那麼若要在 case 之後比對多個字串,就必 需使用字串的異值陣列(Cell Array of Strings): 範例12 : switch 02. m month = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'}; for i = 1: length(month) switch month{i} case {'Mar', 'Apr', 'May'} season = 'Spring'; case {'Jun', 'Jul', 'Aug'} season = 'Summer'; case {'Sep', 'Oct', 'Nov'} season = 'Autumn'; case {'Dec', 'Jan', 'Feb'} season = 'Winter'; end fprintf('%s is %s. n', month{i}, season); end 33
MATLAB 之 程應用:程式流程控制- switch case n 上述範例output如下: Jan is Winter. Feb is Winter. Mar is Spring. Apr is Spring. May is Spring. Jun is Summer. Jul is Summer. Aug is Summer. Sep is Autumn. n n MATLAB 的 switch 指令和 C 語言的 switch 指令略有差別:在 C 語言的 switch 敘述內,每個 case 敘述需加上 break 以跳出該 switch 敘述,而在 MATLAB 則 不必多此一舉。 一般而言,switch–case–otherwise 的執行效率優於 if–then–else 。 34
MATLAB 之 程應用:程式流程控制 補充 - Using fzero function f=fz(x) % evaluate the function fz(x) whose % roots are being sought f=exp(-x)-x; %******************** % Here is the matlab code that uses fz. m to find % a zero of f(x)=0 near the guess x=. 7 % Note that the @ sign is used to tell Matlab that % the name of an M-file is being passed into fzero %******************** x=fzero(@fz, 0. 7) 35
MATLAB 之 程應用:程式流程控制 補充:inline, Example 1 n n This example creates a simple inline function to square a number. >>g = inline('t^2') g= Inline function: g(t) = t^2 n >>g(3) ans = 9 n n You can convert the result to a string using the char function. >>char(g) ans = t^2 36
MATLAB 之 程應用:程式流程控制 補充:inline, Example 2 n f = inline('3*sin(2*x. ^2)') f= n Inline function: f(x) = 3*sin(2*x. ^2) argnames(f) ans = 'x' n formula(f) ans = 3*sin(2*x. ^2) 37
MATLAB 之 程應用:程式流程控制 補充:inline, Example 3 n >>f = inline('sin(alpha*x)') f= n n Inline function: f(alpha, x) = sin(alpha*x) If inline does not return the desired function variables or if the function variables are in the wrong order, you can specify the desired variables explicitly with the inline argument list. >>g = inline('sin(alpha*x)', 'x', 'alpha') g= Inline function: g(x, alpha) = sin(alpha*x) 38
MATLAB 之 程應用:程式流程控制 補充 – inline , Example 4 func=inline(’exp(-x)-x’, ’x’); x=0: . 01: 1; f=func(x); plot(x, f, ’r-’) 39
MATLAB 之 程應用:程式流程控制 切線法 (Secant method) 求根 % script file: secant 01. m clear; close all; %****************** % Define the function as an in line function %****************** func=inline(’exp(-x)-x’, ’x’); % First plot the function x=0: . 01: 2; f=func(x); plot(x, f, ’r-’, x, 0*x, ’b-’) %****************** % From the plot the solution is near x=. 6 % Secant method to solve the exp(-x)-x = 0 % Use an initial guess of x 1=0. 6 %****************** x 1=0. 6; % find f(x 1) f 1=func(x 1); % find a nearby second guess x 2=0. 99*x 1; % set chk, the error, to 1 so it won’t trigger % the while before the loop starts chk=1; % start the loop while chk>1 e-8 % find f(x 2) f 2=func(x 2); % find the new x from the straight line approximation and print it xnew = x 2 - f 2*(x 2 -x 1)/(f 2 -f 1) % find chk the error by seeing how closely f(x)=0 is approximated chk=abs(f 2); % load the old x 2 and f 2 into x 1 and f 1; then put the new x into x 2 x 1=x 2; f 1=f 2; x 2=xnew; end 41
MATLAB 之 程應用:程式流程控制 切線法 (Secant method) 求根 script file: secant 02. m func=inline('exp(x)-3*x', 'x'); x=0. 6159 x=1. 5121 42
MATLAB 之 程應用:程式流程控制 function show. Nearest. Point 1(action) global h 0 h 1 h 2 h 3 h 4 x 1 y 1 if nargin==0 action='b'; end x 1=linspace(0, 4*pi, 30); y 1=sin(x 1); plot(x 1, y 1, 'r-o') axis equal % 43
MATLAB 之 程應用:程式流程控制 switch(action) case 'b' set(gcf, 'windowbuttonmotionfcn', 'show. Nearest. Point 1 a') case 'a' curr. Pt=get(gca, 'Current. Point'); x 2=curr. Pt(1, 1); y 2=curr. Pt(1, 2); Minx=sqrt((x 2 -x 1). ^2+(y 2 -y 1). ^2); n=find(Minx==min(Minx)); line(x 1(n), y 1(n), 'marker', 'o') location=[num 2 str(x 1(n)) ', ' num 2 str(y 1(n))]; %text(x 1(n), y 1(n), loction); %顯示在點上 text(x 2+. 2, y 2, location); %顯示在游標旁 end 44
- Slides: 44