min-hung Chen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # INTRODUCTION TO SCIENTIFIC COMPUTING SOFTWARE ~~2018 2019~~ 2021 Fall --- ## 公告 12/16: webex直播網址 請參考moodle 12/9: [webex直播網址](https://nckucc.webex.com/meet/z9408034) 12/2: [webexx連結](https://nckucc.webex.com/nckucc/j.php?MTID=mfe3d28fd6c2edeb650a8f133b87ba4b8) 11/25: 今天[webexx連結](https://nckucc.webex.com/nckucc-tc/e.php?MTID=m9001c0dfe523abd3ef119e6efa0f75d0) 10/28: 老師的電腦目前有點慢,請先參考第四章 loops的部分操作 10/14: 老師的電腦有點問題,請先下載Chap2_MATLAB_basics.ppt檔案 自行操作。 ## 參考資料 * [2016上課筆記](https://hackmd.io/AplidFuFTT-sNX3ma4LlWQ) ## ㄧ些規範 電腦室請勿飲食([老師有特權XD](https://youtu.be/XiPwh0jy0EQ?t=18m07s)): * 飲料打翻,洗鍵盤是很麻煩的(如果是筆電會更慘),[google](http://tinyurl.com/zt4kt2y)就可以找到一堆求救文。 * 食物碎屑會掉入鍵盤縫隙。 ## Python筆記 [Python筆記本連結](https://hackmd.io/s/HJxVq2KMe) ---- ## Hackmd {%youtube YhAR6hiSl9w%} [markdown 簡報製作與 hackmd 簡介](https://youtu.be/YhAR6hiSl9w) ## Manifold Learning * https://sites.google.com/view/manifoldlearning2020 * https://sites.google.com/view/manifoldlearning2020/%E9%A6%96%E9%A0%81/matlab-codes * https://drive.google.com/file/d/1YgQ08LZc7ssA0exv7ipb0dWOQ-xivGxI/view * --- ##TTopic 1: Course Preparation and Python ### Matlab 相關 * [授權軟體下載中心](https://www.cc.ncku.edu.tw/download/) * 請下載MATLAB 單機版(Windows+Linux/Mac)(單人適用) 1. 先至MATLAB官網註冊帳號 https://www.mathworks.com/ 2. [註冊及安裝說明](https://reurl.cc/xG4roz) 3. [MATLAB Installation Guide](https://goo.gl/4EgAmS) 4. [如何在已經裝好的MATLAB上加裝新的Toolbox](https://goo.gl/7oGXbo) 5. [MATLAB線上講堂](http://www.terasoft.com.tw/academia/TAHResourcekit/index.asp?s=NCKU#tabs-2) :::warning 請注意! 一、官網註冊帳號時,一定要使用成大信箱(@ncku.edu.tw 或 @mail.ncku.edu.tw 或 @gs.ncku.edu.tw)收認證信,該帳號才可成功取得授權。(久未登入需先至官網再次驗證信箱才可使用) 二、電腦名字(使用者名稱)不可為中文!若遇到username錯誤,請新增一英文名字使用者帳號,並登入該使用者帳號後再進行安裝。 三、MATLAB各版本皆可至官網上登入後選取下載。 四、官網有提供mac版。 ::: ### Python 相關 * [Google Colab](https://colab.research.google.com/notebooks/intro.ipynb?utm_source=scs-index) * [Google Colaboratory–適合Python初學者的雲端開發環境](https://www.cc.ntu.edu.tw/chinese/epaper/0052/20200320_5207.html) * [Google Colab相關設定- hackmd](https://hackmd.io/@wiimax/HJuUPnPQr?fbclid=IwAR0gOwz6slT-n8PIbrRFhbzBg03j7GRSIt6MHCiIrovCEKCj-QZhc9KiMpM) * [Google Colab教學!新手Python開發環境推薦【新手Python練習】](https://yc-note.com/python/google-colab-python/) * [雲端基礎教學(2) colab基本操作與建議](https://ithelp.ithome.com.tw/articles/10217962) * [codecademy: Learn Python 2](https://www.codecademy.com/learn/learn-python) * [python2 與 python3的主要差異](https://www.itread01.com/content/1545467104.html) :::info * 目前大部分python的模組應該都已經改為python 3,所以應該直接學python 3。 * 但是目前線上**免費**學習平台我沒找到適合的,所以暫時還是建議大家在codecademy上學習 python **2**,再自行轉換為python3 在google colab上做筆記。 ::: * [先前做的筆記本 MyPythonNotebook.ipynb](https://github.com/minhung/MyPythonNote/blob/master/MyPythonNotebook.ipynb) * https://www.learnpython.org/ * [Anaconda下載連結網址](https://www.anaconda.com/products/individual-d#download-section) * [使用sympy和微積分的各種玩耍.ipynb by 蔡炎龍](https://nbviewer.jupyter.org/github/yenlung/Math-in-Jupyter/blob/master/%E4%BD%BF%E7%94%A8sympy%E5%92%8C%E5%BE%AE%E7%A9%8D%E5%88%86%E7%9A%84%E5%90%84%E7%A8%AE%E7%8E%A9%E8%80%8D.ipynb?fbclid=IwAR2kmD2MyG3aKYRMS5hqVQFG5Bqk5ExVRLcWFzKxE7Ldb6EUKWOqS1WvGzQ) --- ### Homework 1 :::info * moodle先前有一個Homework 1是要求以mupad完成的作業,那是舊課程的作業,不必做。 * 因為新版matlab已經把mupad移除,所以我們這個課程也不會教mupad * 為了方便助教修改,作業1內容修改為新的版本(題目和舊課程的mupad作業類似) ::: * ~~完成[codecademy: Learn Python 2](https://www.codecademy.com/learn/learn-python)課程至Loops部分同時製作筆記~~ * ~~以matplotlib繪圖(三個函數)~~ * ~~使用sympy解決微積分課本中的三種類型題目:極限、微分、積分;每種類型請各做三個例題。~~ * ~~請貼上個人照片~~ * ~~繳交時請繳交ipynb檔以及轉換的pdf檔~~ 完成[codecademy: Learn Python 2](https://www.codecademy.com/learn/learn-python)課程至Loops部分~~同時製作筆記~~ #### Note * ID = the last 4-digits of Your Student ID Number * Do the version_1 if your student id is odd; do the version_2 if your student id is even. * 第一題無窮級數和請參考:[Calculus with Python-Summations](https://calc-again.readthedocs.io/en/latest/tutorials/03-summations.html) * 注意python 的次方運算是"**"不是"^" * 第五題的mod是[同餘](https://zh.wikipedia.org/wiki/%E5%90%8C%E9%A4%98),python中的運算子是 "%" * 1. 請以學號為檔名:" (學號)_hw1.pdf "," (學號)_ipynb " :::info 第一題(特別是Version 1)有點問題,請參考 [Example0916.ipynb](https://colab.research.google.com/drive/1K1OR-484eb5SsKeO7gf2pPdzbynjh8ZD?usp=sharing) ::: #### Version 1 (if your student id is odd) 0. 完成[codecademy: Learn Python 2](https://www.codecademy.com/learn/learn-python)課程至60%,同時截圖上傳: * 登入 codecademy後,點選右上角的icon選擇Profile * 截圖需包含你的姓名或是學號,以及Latest Courses: Learn Python 2 * 參考以下截圖 ![](https://i.imgur.com/8t1OIOf.jpg) 1. Compute: $$\sum_{n=1}^{\infty} \frac{(-3)^{n-1}}{4^{n}}$$ 2. Plot the function $$f(x)=\frac{sin(\pi x)}{\pi x}, x\in[0,5\pi]$$ 3. Integral of the function $$\int \frac{\ln(x)}{x} dx$$ 4. Compute: $$\frac{d}{dx} x^{\sqrt{x}}$$ 5. Calculate $$74^{\text{(ID)}} \quad (\text{mod }14)$$ #### Version 2 (if your student id is even) 0. 完成[codecademy: Learn Python 2](https://www.codecademy.com/learn/learn-python)課程至60%,同時截圖上傳: * 登入 codecademy後,點選右上角的icon選擇Profile * 截圖需包含你的姓名或是學號,以及Latest Courses: Learn Python 2 * 參考以下截圖 ![](https://i.imgur.com/8t1OIOf.jpg) 1. Compute: $$\sum_{n=1}^{\infty}\frac{e^{n}}{6^{n-1}}$$ 2. Plot the function $$g(x)=\frac{cos(\pi x)}{3\pi x}, x\in[-2\pi,2\pi]$$ 3. Integral of the function $$\int x\ln(x) dx$$ 4. Compute: $$\frac{d}{dx} x^{\sin{x}}$$ 4. Calculate $$74^{\text{(ID)}} \quad (\text{mod }11)$$ --- ## Chapter 2: Matlab Basic * I/O * n = input('number of the matrix dim => ?') * name = input(' Your Name =>? ','s') * Matrix (mxn matrix) * A(i,j) = A(i+(j-1)*m) * "end" * String * str1 = ['The value of pi = ' , num2str(pi)] * str2 = strcat('The value of pi = ' , num2str(pi)) * str2(10:15) ---- #### matlabFunction 底下程式是先以symbolic的模式產生一個對角線為d的對角矩陣,之後再以matlabFunction將結果轉為函數使用 ``` syms d m=eye(3) M=d*m Mfun = matlabFunction(M) val_d=input('d=') Mfun(val_d) ``` ---- #### Plot 繪圖功能簡介 * 單一函數圖形繪製 ``` %figure(1) x = 0:0.1:10; y = x.^2-10.*x+15; plot(x,y); title('Plot of y_{fun} = x^2-10*x+15') % 如果想使用latex輸出漂亮數學符號的話可以參考底下指令 %title('$\hat{\psi}$','Interpreter','latex') xlabel('x'); ylabel('y'); grid on; print -djpeg fig_ch2.jpeg ``` * * 請檢視 plot, title, xlabel, ylabel, grid, print 等指令的使用說明(help, doc) * 改寫程式碼, 看有何影響 * 注意 ".^", ".*"的使用 * 使用圖形介面(GUI)得到相同效果 ---- * 多個圖形繪圖 ```maltab= %figure(2) x2 = 0:pi/100:2*pi; y1 = sin(2*x2); y2 = 2*cos(2*x2); plot(x2, y1,'ro-.' ); hold on; plot(x2, y2,'gx:'); hold off %plot(x2, y1,'ro-.',x2, y2,'gx:'); legend('sin(2x)','2cos(2x)','Location','NorthWest'); text(1.5, 0.5, 'sin(2x)') text(3.3, 1.5, '2cos(2x)') ``` * * 注意hold on, hold off的使用 * 檢視legend的說明文件 * 進階功能 ```maltab=+ set(gca,'xtick',[0 1/2*pi pi 3/2*pi 2*pi]) set(gca,'xticklabel',{'0','1/2 pi','pi','3/2 pi','2 pi'}) ``` ---- * 額外的繪圖功能 (Chap3_branching_statement.ppt 後半) * 範例1 ```maltab= x = -2.5*pi:pi/100:2.5*pi; y1 = sin(2*x); y2 = 2*cos(2*x); plot(x, y1,'ro-.'); hold on plot(x, y2, 'gx:'); hold off legend('sin(2x)','2cos(2x)','Location','NorthWest'); text(1.5, 0.5, 'sin(2x)') text(3.3, 1.5, '2cos(2x)') xlabel('x'); ylabel('y'); title('Plot figure of sin(2x) and 2cos(2x)'); set(gca,'xtick',[-2*pi -pi 0 pi 2*pi]) set(gca,'xticklabel',{'-2 pi','- pi','0','pi','2 pi'}) ``` ---- * * 範例2 (subplot 的使用) ```maltab= x = -2.5*pi:pi/100:2.5*pi; y1 = sin(2*x); y2 = 2*cos(2*x); z1 = exp(x/10); z1 = z1.*y2; z2 = y1.*y2; subplot(2,2,1) plot(x, y1,'r'); title('plot sin(2x)'); subplot(2,2,2) plot(x, y2, 'g'); title('plot 2 cos(2x)'); subplot(2,2,3) plot(x, z1, 'b'); title('plot 2cos(2x)exp(x/10)'); subplot(2,2,4) plot(x, z2, 'm'); title('plot 2cos(2x)sin(2x)'); ``` --- ### Homework 2: Matlab [](https://hackmd.io/@RJ/HkqXCBedH?type=view) #### Note 0. Write a Matlab script file to slove following problems. (load data2021.mat for this homework) 1. Take a screenshot of results of Prob. 1 - Prob. 3 and combine with the result of Prob. 4 to generate “StudentID_hw2.pdf”. 2. Upload your homework to moodle as “StudentID_hw2.pdf” file and a matlab file as “StudentID_hw2.m”. It should contain your **name, student id, codes and the results of your codes.** 3. Feel free to ask TA, if you have problems about this homework. ---- 1. Use the command strcat function to show “My StudentID:(your ID)” 2. Use the command load to read $Q$ and $A$ from data.matand calculate the following problems (a) $Q^{-1}AQ$ (b) $Q^{-1} A^5Q$ 3. Solve the following system of equation using the martix form $Ax=b$ \begin{cases} x-y+2z=1 \\ 2x+2y+3z=9 \\ 3x+y+2z=7 \\ \end{cases} 4. Use plot(x,y) to graph $y=2\sin(3x)-5\cos(7x)$, $x \in [-2\pi,2\pi]$ #### HW2 說明&提示與補充: 0. 讀取 `data2021.mat` 1. 字串合併:利用 `strcat()` 把你的ID字串與 `mystr` 變數合併成新的字串 2. 矩陣對角化:在紙上計算一個矩陣的高次方時,通常不好算且容易算錯。如果我們找到了可逆的 $Q$ 矩陣,使得 $Q^{-1}AQ=D$ 是對角矩陣,則稱為 $A$ 是可對角化的。此時 $A=QDQ^{-1}$,透過 $A^{k}=(QDQ^{-1})^k=QD^kQ^{-1}$ 便可以很容易地算出 $A^k$。而對角矩陣 $D$ 上的元素為矩陣 $A$ 的特徵值。 <br><br>(a)小題即是提供 $Q$ 與 $A$ 矩陣,驗證 $Q^{-1}A^kQ=D^k$<br>(b)小題利用第一堂課提到的`eig()` 函數來計算矩陣 $A$ 的特徵值。至於如何把他放成矩陣的樣子,請使用 `help eig` 查詢。<br><br>[WIKI : 可對角化矩陣](https://zh.wikipedia.org/wiki/可对角化矩阵)<br>[WIKI : 特徵向量](https://zh.wikipedia.org/wiki/特征向量) :::info 這種處理方式有很多應用,比方說解微分方程系統時 $$ \frac{d}{dt}U = AU, $$ 形式上我們可以把解寫成 $$ U(t)=U(0) e^{tA}. $$ 其中的$e^{tA}$可以用對角化的技巧得到 ::: 3. 將線性方程組寫成 $LX=R$ 的樣子,當 $L$ 存在反矩陣,可以利用兩邊同乘 $L^{-1}$ 來得到 $X=L^{-1}R$ <br> 4. 使用plot指令繪圖 :::warning 由於是在script檔完成各題的工作,所以變數名稱請小心不要衝突 ::: --- ## Chapter 3: branching_statement * if-else * 範例: 一元二次方程式 ```maltab= disp ('This program solves for the roots of a quadratic '); disp ('equation of the form A*X^2 + B*X + C = 0. '); a = input ('Enter the coefficient A: '); b = input ('Enter the coefficient B: '); c = input ('Enter the coefficient C: '); % Calculate discriminant discriminant = b^2 - 4 * a * c; % Solve for the roots, depending on the value of the discriminant if discriminant > 0 % there are two real roots, so... x1 = ( -b + sqrt(discriminant) ) / ( 2 * a ); x2 = ( -b - sqrt(discriminant) ) / ( 2 * a ); disp ('This equation has two real roots:'); fprintf ('x1 = %f\n', x1); fprintf ('x2 = %f\n', x2); elseif discriminant == 0 % there is one repeated root, so... x1 = ( -b ) / ( 2 * a ); disp ('This equation has two identical real roots:'); fprintf ('x1 = x2 = %f\n', x1); else % there are complex roots, so ... real_part = ( -b ) / ( 2 * a ); imag_part = sqrt ( abs ( discriminant ) ) / ( 2 * a ); disp ('This equation has complex roots:'); fprintf('x1 = %f +i %f\n', real_part, imag_part ); fprintf('x1 = %f -i %f\n', real_part, imag_part ); end ``` ---- * switch-case-otherwise * 範例: 根據月份來判斷其季別(1) ```maltab= 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 ``` ---- * * 範例: 根據月份來判斷其季別(2) ```maltab= 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 ``` --- ## Chapter 4: Loops 迴圈 這個章節主要在說明迴圈的使用方式,同時介紹了如何使用向量式計算來加速。 ### 簡介 * for ```maltab= for ii = 1:10 fprintf('The value of the dummy variable is: %d\n', ii); end ``` * * 修改 for 之後的陳述(ii = 1:0.5:10, ii = [5 9 7]),觀察結果 * while ```maltab= ii =0; while ii < 10 ii = ii+1; fprintf('The value of the dummy variable is: %d\n', ii); end ``` ---- ### 計算某年的第幾天 ``` year = input('year = '); month = input('month = '); day = input('day = '); if mod(year,400) == 0 leap_day = 1; elseif mod(year,100)==0 leap_day = 0; elseif mod(year,4)==0 leap_day = 1; else leap_day = 0; end day_of_year = day; for ii = 1:month-1 % Add days in months from January to last month switch (ii) case {1,3,5,7,8,10,12}, day_of_year = day_of_year + 31; case {4,6,9,11}, day_of_year = day_of_year + 30; case 2, day_of_year = day_of_year + 28 + leap_day; end end fprintf('Year = %d, Month = %d, Day = %d\n',year,month,day) fprintf('Day of Year = %d\n',day_of_year) ``` ---- ### 預先分配陣列與向量化陣列(重要) * 範例1 ```maltab= n = 200000; tic; for ii = 1:n square1(ii) = ii^2; end fprintf('Total cpu time = %g \n', toc); ``` * 範例2 (預先分配陣列) ```maltab= n = 200000; tic; square2 = zeros(1,n); for ii = 1:n square2(ii) = ii^2; end fprintf('Total cpu time = %g \n', toc); ``` ---- * 範例3 (向量化計算) ```maltab= n = 200000; tic; ii = 1:n; square3 = ii.^2; fprintf('Total cpu time = %g \n', toc); ``` ---- ### break 與 continue * break會停止迴圈內的執行,並將程式的控制權,轉移到緊接在迴圈end之後的下一個宣告。 * continue會停止目前迴圈的執行,將程式的控制權傳回迴圈的最上層。 ---- * 範例 (break) ```maltab= for ii = 1:5 if ii == 3 break; end fprintf('ii = %d\n',ii); end disp(['End of loop!']); ``` * 範例 (continue) ```maltab= for ii = 1:5 if ii == 3 continue; end fprintf('ii = %d\n',ii); end disp(['End of loop!']); ``` ---- ### 邏輯陣列 ```maltab= a = [1 2 3;4 5 6;7 8 9] b = a>5 ``` ---- #### 邏輯陣列與向量優化 * 範例1 ```maltab= a = [1 2 3;4 5 6;7 8 9] c = zeros(size(a)); for ii = 1:size(a,1) for jj = 1:size(a,2) if ( a(ii,jj) > 5 ) c(ii,jj) = sqrt(a(ii,jj)); end end end ``` * 範例2 (優化/向量式計算) ```maltab= a = [1 2 3;4 5 6;7 8 9] b = a>5 c = zeros(size(a)); c(b) = sqrt(a(b)) ``` ---- ### 延伸閱讀 * [Improving the Speed of MATLAB Calculations](http://web.cecs.pdx.edu/~gerry/MATLAB/programming/performance.html) * [Matlab (scholarpedia)](http://www.scholarpedia.org/article/MATLAB): 請看 Interpretation, just-in-time compilation, and performance的部分 --- 範例題目:畫一個piecewise-defined fun $$ f(x)= \left\{\begin{array}{cl} x,& \textrm{if }x<0,\\ 0,& \textrm{if }0<=x<=1,\\ x^2,& \textrm{if }x>1. \end{array} \right. $$ 繪圖範圍: [-2,2] ```maltab= clear all;close all xr = -2:0.1:2; figure(1) for ii = 1:length(xr) if xr(ii) < 0 yr(ii) = xr(ii); elseif xr(ii) <=1 yr(ii) =0; else yr(ii) =xr(ii)^2; end end plot(xr,yr,'bo-') ``` * 注意, 上述範例程式碼使用的畫圖樣式'bo-', 會以實線將marker 'o' 連起來, 所以函數不連續處也會被連起來. * 一個比較簡單的作法是只標記點(使用'.'), 不畫出線, 同時使用更多的點描述這個函數. --- ### 利用邏輯矩陣及向量式運算造出方波、三角波 範圍:`t=0:100` #### 方波函數 $f_1(t)=\left\{\begin{array}{ll}1, &0 \le t< 5 \\ 0, &5 \le t < 10\end{array}\right.$ $f_1(t)=f_1(t+10)$ #### 三角波函數 $f_2(t)=\left\{\begin{array}{ll}\frac{1}{5}, t& 0 \le t<5 \\ -\frac{1}{5}t+2, &5 \le t < 10\end{array}\right.$ $f_2(t)=f_2(t+10)$ ###### 方法一 ```matlab= t=1:44100; a=mod(t,100); a(mod(t,100)<=50)=a(mod(t,100)<=50)/50; a(mod(t,100)>50)=-a(mod(t,100)>50)/50+2; plot(a) ``` ###### 方法二 >[name=Pei-Sheng Chuang] ```matlab= t = 0:100; %方波 sq = mod(t,10) < 5; %三角波 tr = mod(t,10).*(mod(t,10)<5)/5 + (2-mod(t,10)/5).*(~(mod(t,10)<5)); ``` #### 作業繳交格式: * "學號.m檔"、"結果截圖"請一起放進資料夾,使用zip壓縮 * 檔名:學號.zip * plot函數的title: 學號 姓名 ---- ---- #### Bisection Method: 以二分法的方式找函數為零處 * sample code : [bisection.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch4/bisection.m) * reference : [Wiki-二分法](https://zh.wikipedia.org/wiki/二分法_(數學)) ```matlab clear all left=0; right=2; epsilon=1e-5; fprintf('The left-enpoint is %g, cos(left)=%g \n',left,cos(left)) fprintf('The right-enpoint is %g, cos(right)=%g \n',right,cos(right)) iter=0; while (right-left) > 2*epsilon iter=iter+1; l_value=cos(left); r_value=cos(right); midpoint = (right+left)/2; m_value=cos(midpoint); fprintf('The midpoint is %g, cos(midpoint)=%g \n',midpoint,cos(midpoint)) if (l_value *m_value <0) right=midpoint; elseif (r_value *m_value <0) left=midpoint; else fprintf('The root is %g\n',midpoint) break end fprintf('Iteration %d\n',iter); fprintf('The left-enpoint is %g, cos(left)=%g \n',left,cos(left)) fprintf('The right-enpoint is %g, cos(right)=%g \n',right,cos(right)) end ``` --- #### Newton's method * reference : [Wiki-牛頓法](https://zh.wikipedia.org/wiki/牛顿法) --- ## Chapter 5: 使用者自訂函數 [ 第五章範例程式](https://www.math.ncku.edu.tw/~mhchen/matlab11f/#tutorial) 函式格式(開頭): function [out1, out2, ...] = funname(in1, in2, ...) % Comments statements * out1, out2, ... : 是輸出引數 * in1, in2, ... : 是輸入引數 * funname: 是函式名稱,這個名稱需與檔案(.m)名稱相符 * %Comments: 裡包含函式說明 * statements: 函式主體 ### SSORT ``` a = [8,4,6,1,5]; nvals = size(a,2) for ii =1:nvals; iptr = ii; for jj=ii+1:nvals if a(jj)<a(iptr) iptr = jj; end end fprintf('Iteration %d: Old Array',ii) display(a) fprintf('the index of smallest element is %d, value = %d\n', iptr,a(iptr)); if iptr~= ii temp = a(ii); a(ii)=a(iptr); a(iptr)=temp; end display('New Array') display(a) end ``` --- ### Function ``` fzero('cos',[0 pi]) fzero(@cos,[0 pi]) myfun = @(x,c) cos(c*x); fzero(@(x) myfun(x,1),[0 pi]) myfun2 = @(x) myfun(x,1) fzero(@(x) myfun2(x),[0 pi]) fzero(myfun2,[0 pi]) ``` #### eval and feval ``` eval('sin(pi/4)') feval('sin',pi/4) feval(@sin,pi/4) myfun =@(x) sin(x) feval(myfun,pi/4) ``` ---- ### error與warning * error:顯示錯誤的訊息,並放棄執行產生錯誤的函式 * warning:顯示警告的訊息,並繼續執行函式 以下範例程式碼是一個迴圈程式,在i>5時會發出警告(warning),但是程式會繼續執行。在i=9時會使用error中斷程式: ```matlab for i =1:10 if i >5 warning('i is bigger than 5, i = %d',i) end if i == 9 error('Too dangerous. Get Me Outta Here, i = %d',i) end end ``` ---- ### nargin, nargout, nargchk * nargin:函式實際輸入變數的個數 * nargout:函式實際輸出變數的個數 * nargchk:假如用來呼叫函式的引數太少或太 多,這個函式將傳回一個標準的錯誤訊息 ```matlab function myy = stupidfun(x,y) % Check for a legal number of input arguments. display('Check for a legal number of input arguments.'); msg = nargchk(1,2,nargin); error(msg); % If the y argument is missing, set it to 0. if nargin < 2 y = 0; end myy = y; end ``` [2019 HW3](https://hackmd.io/@RJ/108matlabhw3) ### Homework 3 Matlab函數練習 #### Note * Upload your homework to moodle as “StudentID_hw3.pdf” file and a matlab file as “StudentID_hw3.m”. It should contain your name, student id, codes and the results of your codes. * Feel free to ask TA, if you have problems about this homework. #### Write a Matlab script file to slove following problems. (Use the command function to solve this homework) 1. Use the command for and if-else to graph the triangle wave $f(x)$ * For $x \in [0,20]$ * In blue dashed line with “o” markers * Name the title as your student ID. * $f(x) = f(10+x)$ $$ f(x)= \begin{cases} \frac{-x}{5} \quad\quad &\text{if}~~ 0 \leq x < 5 \\ \frac{x}{5}-2 &\text{if}~~ 5 \le x < 10 \\ \end{cases} $$ 2. Graph the square wave $g(x)$ without for-loop * For $x \in [0,20]$ * In yellow dotted line with “+” markers * Name the title as your student ID. * $g(x) = g(10+x)$ $$ g(x)= \begin{cases} 1 \quad\quad &\text{if}~~ 0 \leq x < 5 \\ -1 &\text{if}~~ 5 \le x < 10 \\ \end{cases} $$ 3. Graph the functions $f(x)$ and $g(x)$ from Q1 and Q2 in the same coordinate system, that is, in the same figure, with textbox to identify each of them. 4. Graph the square wave $g(x)$ without for-loop * For $x \in [0,20]$ * In black dash-dotted line with “*” markers * Name the title as your student ID. * Graph this function in a new coordiante system. Do not graph with Q1 and Q2. * $$ g(x)= \begin{cases} \frac{-x}{5} \quad\quad &\text{if}~~ 0 \leq x < 5 \\ -1 &\text{if}~~ 5 \le x < 10 \\ \frac{x}{5}-2 &\text{if}~~ 10 \le x < 15 \\ 1 &\text{if}~~ 15 \le x < 20 \\ 0 &\text{if}~~ x = 20. \\ \end{cases} $$ :::info 原先題目在$x = 20$沒有設好,補上定義。 ::: --- ### 2021/11/8 課堂作業 補充說明 作業說明如下: 撰寫一個function,依照輸入的函數以及範圍畫出函數圖形,同時以切線法找到函數的根。 * 畫圖函數 f(x):為function的輸入引數 * 畫圖函數的微分 f'(x):為function的輸入引數 * 繪圖範圍 [a,b] 為function的輸入引數 * 請將圖形的title也設為function的輸入引數 * 切線法求根部分,請使用input指令輸入一個初始值,預設收斂條件為前後兩個迭代點差距在$10^{-10}$以內 * 如果$|f(x_{new})|<10^{-10}$,也視為找到根,收斂。 * 為了避免無窮迴圈,割線法求根迭代次數上限設為20次 * 請將迭代點畫在函數圖形上。 * 請在command window中測試你的function,將結果截圖上傳(以學號為檔名) 這是一個比較複雜的作業,建議先分成二個小程式撰寫測試,成功後再合併: * 畫圖部分,基本上延續11/4的課堂作業,但是加入輸入畫圖函數 $f(x)$部分。 :::info 建議使用function handle方式,可以參考[2019/10/31 課堂作業參考](https://hackmd.io/adA2n_9ZQQy7ujw5JOz66A#20191031-%E8%AA%B2%E5%A0%82%E4%BD%9C%E6%A5%AD%E5%8F%83%E8%80%83) ::: * 切線法求根部分:建議先選取一個測試函數,在根附近選取一個適當的初始點 :::info 可以先試試 $f(x)=x^2-1$,我們知道有二個根, $\pm 1$。可以選$2$做為起始點,使用切線法迭代後會收斂到$1$。 ::: * moodle上有提供ex110b8.m、secentline.m 二個檔案做為參考。secentline.m是使用割線法求根的function,ex110b8.m則是類似這次作業的要求,但是求根是使用割線法(secentline.m) --- ### 2019/10/24課堂作業的一些問題 問題描述如下: :::info 撰寫一個function,依照輸入的範圍畫出函數圖形 * 畫圖函數 $\sin x^2+\cos x$ * 繪圖範圍 [a,b],為function的輸入引數 * 使用nargin等matlab內建變數判斷輸入引數是否足夠,若判斷使用者沒有輸入畫圖範圍,則採用預設範圍[0,1]。 * 請將圖形的title也設為function的輸入引數 * 請在command window中測試你的function,將結果截圖上傳(以學號為檔名) ::: 參考程式 ```= function myplot(mytitle,a,b) msg = nargchk(1,3,nargin); error(msg); if nargin<3 display('Missing [a,b]. Use default range [0,1]') a=0; b=1; end x = linspace(a,b,1001); y = sin(x.^2)+cos(x); plot(x,y) title(mytitle) end ``` ㄧ些問題如下 * nargchk or narginchk nargchk 在以後的版本會被移除,matlab建議改用narginchk或是nargoutchk。如果改用narginchk,2-3行的程式碼改成底下的程式 ``` narginchk(1,3) ``` :::warning narginchk 沒有output,所以寫成`msg=narginchk(1,3)`反而有錯,無法執行。 ::: * script中定義function 有些同學的是在script檔中定義function。比方說,底下的程式(假設存成mytest.m),其中的function內容和先前的myplot funciton相同。這樣的寫法在舊版是不允許的,但是在R2016b或是更新的版本是允許的。 ``` myplot('c12345') function myplot(mytitle,a,b) ... end ``` :::info 這樣定義的function是local function,其它程式無法使用這個function。參考底下連結 https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html ::: * 函數$\sin x^2+\cos x$。如果要使用向量式計算(x是一個array時),程式如下 ``` sin(x.^2)+cos(x) ``` * 在function 中 使用input輸入a,b 有些同學把a,b值的輸入放在function裡。基本上程式沒有甚麼問題,不過作業的題目是如果呼叫這個function時沒有輸入a,b就改用預設值[0,1],所以程式的功能和我們的要求稍有不同。 * end of function 一般來說,程式區塊的結尾必須要有end,比方說if,for 最後都有end來標示if或是for的結束。function的宣告也一樣,我們應該要在function結束的地方加end,不過如果整個檔案就只有一個function,matlab可以判斷function結束的地方就可以忽略(不過還是建議加end)。 * 變數使用請小心 這個function沒有要求傳回值,所以不需要有output argument。但是加上output argument也不會妨礙程式執行,只是要小心不要犯錯,比方底下的程式因為把程式內建的plot函數重新定義,所以程式無法執行 ``` function plot=myplot(mytitle,a,b) msg = nargchk(1,3,nargin); error(msg); if nargin<3 display('Missing [a,b]. Use default range [0,1]') a=0; b=1; end x = linspace(a,b,1001); y = sin(x.^2)+cos(x); plot(x,y) title(mytitle) end ``` ### 2019/10/31 課堂作業參考 以下的程式碼(script)會呼叫檔內的myplot function,依照給的參數(函數、範圍)繪圖 ``` myfunin = @(x) cos(x.^2); %myfunin = 'cos'; mytitlein = 'c12345'; ain = 0; bin = 1; myplot(mytitlein,myfunin,ain,bin) function myplot(mytitle,fun,a,b) narginchk(0,4) if nargin ==0 mytitle = 'Please Input Your Title'; end if nargin <2 fun =@(x) sin(x.^2) end if nargin <4 a=0; b=1; end t=linspace(a,b,1001); y = feval(fun,t); plot(t,y) title(mytitle) end ``` :::info 程式中的function myplot只能在這個script檔中呼叫,無法被其他檔案或是在command window中呼叫。如果要讓這個function可以被其他程式呼叫,必須寫成獨立的function檔。 ::: * https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html * 將輸入字串轉換為函數的幾個做法: * https://www.mathworks.com/help/symbolic/matlabfunction.html * https://www.mathworks.com/help/symbolic/str2sym.html ``` syms x mystr = 'x^2+1' myeq = str2sym(mystr) mydf = diff(myeq,x) t =linspace(0,1,101); mydfh = matlabFunction(mydf) y = mydfh(t); plot(t,y); ``` * https://www.mathworks.com/help/matlab/ref/str2func.html ``` t = linspace(0,1,101); mystr = '@(x) x.^2+1'myfh = str2func(mystr) y=myfh(t); plot(t,y) y=feval(myfh,t); plot(t,y) ``` * Examine Differences Between str2func and eval * openExample('matlab/ExamineDifferencesBetweenStr2funcAndEvalExample') ### 2018/11/8 黃金比例 [黃金比例](https://zh.wikipedia.org/wiki/%E9%BB%84%E9%87%91%E5%88%86%E5%89%B2%E7%8E%87#%E6%9B%BF%E4%BB%A3%E6%88%96%E5%85%B6%E4%BB%96%E5%BD%A2%E5%BC%8F) $$\phi = 1+1/\phi$$ 迭代公式 $$\phi_{new} = 1+1/\phi_{old}$$ ``` %mygratio phinew = 1; for ii =1:10 phiold = phinew; phinew = 1+1/phiold; fprintf('Iteration %d\n',ii); fprintf('phi_old=%f, phi_new=%f\n',phiold,phinew); end phiroot1=(1+sqrt(5))/(2); phiroot2=(1-sqrt(5))/(2); fprintf('Root =%f\n',phiroot1); phinew = -1; ii=0; while(abs(phinew-phiroot1)>1e-5) phiold = phinew; phinew = 1+1/phiold; fprintf('Iteration %d\n',ii); fprintf('phi_old=%f, phi_new=%f, err=%f\n',phiold,phinew,abs(phinew-phiroot1)); ii = ii+1; end fprintf('Root =%f\n',phiroot1); fprintf('My App. Root =%f\n',phinew); ``` ---- ### pass-by-value :::info 將以下程式碼儲存成一函數檔 ::: ```matlablike function out = sample(a, b) fprintf('In sample: a = %f, b = %f %f\n',a,b); a = b(1) + 2*a; b = a .* b; out = a + b(1); fprintf('In sample: a = %f, b = %f %f\n',a,b); ``` :::info 將以下程式碼儲存成一執行緒檔(testsample.m) ::: ```matlab a = 2; b = [6 4]; fprintf('Before sample: a = %f, b = %f %f\n',a,b); out = sample(a,b); fprintf('After sample: a = %f, b = %f %f\n',a,b); fprintf('After sample: out = %f\n',out); ``` 執行testsample.m 觀察呼叫sample函數過程中,ab變數的變動過程。 ---- #### Example: Selection sort 選擇排序 [選擇排序](https://zh.wikipedia.org/wiki/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F) {%youtube LriMvv9qDrk %} {%youtube Ns4TPTC8whw %} 範例函數 ```matlab function out = ssort(a) % Get the length of the array to sort nvals = size(a,2); fprintf('Your Input') a % Sort the input array for ii = 1:nvals-1 % Find the minimum value in a(ii) through a(n) iptr = ii; for jj = ii+1:nvals if a(jj) < a(iptr) iptr = jj; end end % iptr now points to the minimum value, so swap a(iptr) % with a(ii) if ii ~= iptr. if ii ~= iptr temp = a(ii); a(ii) = a(iptr); a(iptr) = temp; end fprintf('-----------------------\n') fprintf('iter %d',ii) a end % Pass data back to caller out = a; ``` 執行緒檔 ```matlab % Prompt for the number of values in the data set nvals = input('Enter number of values to sort: '); % Preallocate array array = zeros(1,nvals); % Get input values for ii = 1:nvals % Prompt for next value string = ['Enter value ' int2str(ii) ': ']; array(ii) = input(string); end % Now sort the data sorted = ssort(array); % Display the sorted result. fprintf('\nSorted data:\n'); for ii = 1:nvals fprintf(' %8.4f\n',sorted(ii)); end ``` ---- ### Recursive Programming: #### SSORT 連結的程式是以recursive 方式改寫SSORT方法 [My SORT (Main Prog)](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_ssort.m) [Recursive SSORT (function)](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/rec_ssort.m) ---- #### Factorial [recursive algorithm for factorial function]( http://planetmath.org/recursivealgorithmforfactorialfunction) [my_factorial.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_factorial.m) ---- #### Example: Bisection Method(以二分法的方式找函數為零處) [mybisection.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/mybisection.m) [myfun.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/myfun.m) ---- #### Exercise 將mybisection.m改寫為一function (my_bisection_fun.m) input為 a,b兩點: * 輸出 out=(a+b)/2 * 判斷輸入引數數目是否正確(nargchk), 錯誤則輸出錯誤訊息並中斷 * 判斷a,b兩點間是否有根, (f(a)f(b)<0) * 檢查是否有收斂(f((a+b)/2)是否接近0) * 將imax加入選擇性輸入引數 * 將epsilon加入選擇性輸入引數 * 輸入引數包含函數名稱 * 與quickplot 函數整合:在求根前先畫函數圖形 [my_bisection_fun.m]:(http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_bisection_fun.m) [my_bisection_fun_v2.m]:(http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_bisection_fun_v2.m) [my_bisection_fun_v3.m]:(http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_bisection_fun_v3.m) ---- ### Example: Euler Method Use Euler’s method with h = 0.1 to approximate y(1) where y(t) is the solution of the initial value problem: $$dy/dt = y + t; \quad y(0) = 1.$$ Note that the exact solution of this IVP is $y(t) = 2e^t-t-1.$ [Euler method -wiki](http://en.wikipedia.org/wiki/Euler_method) Pseudo code ```clike= Set t=a and y=A Store t and y Repeat while t < b { Set F=f(t,y), t=t+h and y=y+hF Store t and y } ``` [my_euler_ex.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_euler_ex.m) [my_euler_fun.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_euler_fun.m) ---- ### Example: Numerical integration - 矩形法 [Numerical integration - 矩形法 (wiki)](https://zh.wikipedia.org/wiki/%E7%9F%A9%E5%BD%A2%E6%B3%95) [my_rec_integration_ex.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_rec_integration_ex.m) ---- ### 主函數與子函數 [my_nested.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_nested.m) [my_bisection_fun_pri_sub.m](http://math.ncku.edu.tw/~mhchen/iscs2016/ch5/my_bisection_fun_pri_sub.m) --- ### ginput 以下程式讓使用者在圖上選取兩點,決定擷取範圍 ``` imdata = imread('ngc6543a.jpg'); figure(1), imshow(imdata); [x,y] = ginput(2) B=imdata(round(min(y)):round(max(y)),round(min(x)):round(max(x)),:); figure(2), imshow(B) ``` ## Topic: Symbolic Math Toolbox * [Symbolic Math Toolbox 張智星](http://mirlab.org/jang/books/symbolic/) * [Matlab應用_符號運算](https://myweb.ntut.edu.tw/~jcjeng/Computer%20Programs/Matlab_6.pdf) * simple 指令改用 simplify * sym 指令可改用str2sym,比方說 sym('(1+sqrt(5))/2') 改為 str2sym('(1+sqrt(5))/2') * [mix symbolic with function handle](https://www.mathworks.com/matlabcentral/answers/553684-mix-symbolic-with-function-handle) ### Solve Equations: Solve * Solve Multivariate Equations and Assign Outputs to Structure :::warning 投影片中的solve命令方式是舊版的,新版請參考底下說明 ::: ``` >> S = solve([x+y-1==0, x-11*y-5==0]) S = struct with fields: x: [1×1 sym] y: [1×1 sym] >> S.x ans = 4/3 >> S.y ans = -1/3 ``` ### Convert symbolic expression to function handle or file * [Convert symbolic expression to function handle or file](https://www.mathworks.com/help/symbolic/matlabfunction.html): matlabFunction * Convert Symbolic Expression to Anonymous Function ``` syms x y r = sqrt(x^2 + y^2); ht = matlabFunction(r) ``` * Convert Symbolic Function to Anonymous Function ``` syms x y f(x,y) = x^3 + y^3; ht = matlabFunction(f) ``` * Write MATLAB Function to File with Comments ``` syms x f = x^2 + log(x^2); matlabFunction(f,'File','myfile'); ``` Write the MATLAB function generated from f to the file "myfile". ``` function f = myfile(x) %MYFILE % F = MYFILE(X) % This function was generated by the Symbolic Math Toolbox version 8.4. % 01-Sep-2019 00:00:00 t2 = x.^2; f = t2+log(t2); ``` Include the comment Version: 1.1 in the file. ``` matlabFunction(f,'File','myfile','Comments','Version: 1.1') ``` 內容: ``` function f = myfile(x) ... %Version: 1.1 t2 = x.^2; ... ``` * Speed Up Evaluation by Converting Symbolic Function to Anonymous Function ### Converting Function Handle to a Symbolic Function * [Converting Anonymous Function to a Symbolic Function](https://www.mathworks.com/matlabcentral/answers/449489-converting-anonymous-function-to-a-symbolic-function#answer_364896) #### Example 1 ``` v = @(t) exp(1).^(sin(t)) - 1; ``` * sym ``` v = @(t) exp(1).^(sin(t)) - 1; sym(v) %ans = %(3060513257434037/1125899906842624)^sin(t) - 1 % where 3060513257434037/1125899906842624 is an approximation of exp(1) ``` * sym version 2 ``` v = @(t) exp(1).^(sin(t)) - 1; sym t v(t) ``` * str2sym(char(v)) ``` v = @(t) exp(1).^(sin(t)) - 1; str2sym(char(v)) ``` :::warning nested functions 可能失敗 ::: ``` www = @(t) t+1 yyy = @(t) www(t)+1 ``` #### Example 2 ``` v = @(t) exp(sin(t)) - 1; ``` ### 微分function handle 11/25 課堂作業希望可以設計成使用者輸入一個函數後,使用Symbolic Toolbox微分後,使用切線法求根。使用Symbolic Toolbox微分的方法有很多種,比方說讓使用者以字串(string)方式輸入後,轉為symbolic expression後微分,再使用matlabFunction轉換為function handle ``` syms x myf_sym = str2sym('x^2+1') % myf_sym = x^2 + 1 myf =matlabFunction(myf_sym) %myf = function_handle with value: @(x)x.^2+1.0 mydf_sym = diff(myf_sym,x) %mydf_sym = 2*x mydf =matlabFunction(mydf_sym) % mydf = function_handle with value: @(x)x.*2.0 ``` 如果你的程式一開始是轉為function_handle,也可以使用diff指令微分(需要先以syms x指令宣告x 是symbolic變數)。但是微分後是symbolic expression,還是要是用matlabFunction轉為function_handle才能使用 ``` f = 'x^2+1'; syms x myf = str2func(['@(x)' f]) mydf_sym =diff(myf,x) % mydf_sym =2*x mydf = matlabFunction(diff(myf,x)) % mydf = function_handle with value: @(x)x.*2.0 ``` :::info * ['@(x)' f]的目的是將使用者輸入的f加上'@(x)'變成function handle形式的字串,才能使用str2func轉為function handle * 使用whos會看到mydf_sym是symbolic expression ::: #### eval, str2fun * Examine Differences Between str2func and eval * openExample('matlab/ExamineDifferencesBetweenStr2funcAndEvalExample') ``` a=1,b=2,c=3,d=4 x=1 f='a^x+exp(b)+sin(c*x)+d' y = eval(f) % fHandle = eval(['@(x, a, b, c, d) ' f]); y = fHandle(x, a, b, c, d); % fHandle2 = str2func(['@(x, a, b, c, d) ' f]); y = fHandle2(x, a, b, c, d); ``` * [Why is `eval` worse than `str2func` to evaluate a function from a string?](https://stackoverflow.com/questions/46213509/why-is-eval-worse-than-str2func-to-evaluate-a-function-from-a-string) * [Terrible idea](https://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170) * [Alternatives to the eval Function](https://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html) * [Evading eval](https://blogs.mathworks.com/loren/2005/12/28/evading-eval/) * [Matlab - Evaluate Function from String [duplicate]](https://stackoverflow.com/questions/46178175/matlab-evaluate-function-from-string) * [Performance of `eval` compared to `str2func` to evalulate a function from a string](https://stackoverflow.com/questions/46179940/performance-of-eval-compared-to-str2func-to-evalulate-a-function-from-a-stri) ## Topic 6: 圖形介面 ### uicontrol ``` close all clear all h = uicontrol; % 產生按鈕 set(h,'String','請按我!','position',[200 100 160 40]); % 在按鈕表面加入文字「請按我!」 cmd = 'fprintf(''有人按我一下喔!\n''); '; % 定義按鈕被按後的反應指令 cmd2 = 'set(h,''String'',''按我!'',''FontSize'',24,''position'', [200 100 160 100]);'; set(h, 'Callback',cmd2); % 設定按鈕的反應指令 ``` 大部份簡單的題目, 如簡單的猜數字遊戲,Conway的生命遊戲, 畫函數圖形, 可以藉由加上適當的圖形介面作為期末專題 參考範例: [gui_example.zip](http://www.math.ncku.edu.tw/~mhchen/matlab/gui_example.zip): :::info 無法下載時,請連到[我在系上的舊課程連結](https://www.math.ncku.edu.tw/~mhchen/matlab/) Announcements: 6/13 有檔案連結 ::: * gui_ex1.m: 按下按鈕後會將累計按下次數顯示在text處 myplot.m: 使用popupmenu選擇後, 按下按紐會畫出對應的函數圖形 * myplot2.m: 搭配微分方程數值解, 將解出的數值解對時間作圖同時畫出phase portrait. * num_guess.m: 在Edit Text欄位輸入數值後, 經計算後結果顯示在底下框框. 可做為猜數字遊戲的參考. 參考資料 * [MATLAB之工程應用- 第十三章 圖形介面](http://bime-matlab.blogspot.com/2006/12/blog-post_31.html) * [Creating A Graphical User Interface with MATLAB -Video](http://www.youtube.com/watch?v=D_hmws6dwgg) * [Creating Graphical User Interfaces - MathWorks](http://www.mathworks.com/help/techdoc/creating_guis/bqz79mu.html) * [MATLAB程式設計:入門篇(張智星)](http://mirlab.org/jang/books/matlabProgramming4beginner/) * [What's the difference between using "deploytool" and Matlab Compiler?](https://stackoverflow.com/questions/45297068/whats-the-difference-between-using-deploytool-and-matlab-compiler) * [Matlab GUI 學習筆記](https://pamelanowwork2021.medium.com/matlab-gui-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-1-%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B8-7020fe505ba4) ---- ### 2018/12/13 筆記 #### part 1 * 使用guide開啟新的gui * 在gui中加入兩個axes,一個pushbutton * 在pushbutton的Callback function中使用以下指令在指定的axes中繪圖 ``` t = linspace(0,2*pi,101); y1 = sin(t); axes(handles.axes1); plot(t,y1); ``` :::info 上面指令會在axes1中繪圖,若要改為axes2,則指令改為 axes(handles.axes2); ::: * 加入兩個Edit Text,分別改標籤(tag)為inputa以及inputk * 使用get指令取得inputa以及inputk兩個文字輸入框中輸入的值(因為是Edit Text,性質是String,底下指令是以str2num將其改為數值) ``` k = str2num(get(handles.inputk,'String')); ``` ### 2021/12/16 筆記 #### part 1 * 加入一個static text,一個Edit Text * 假設static text的Tag為OutputText,Edit Text的Tag為myText * 在myTex的Callback加入以下指令 ``` myinput = get(handles.myText, 'String'); set(handles.OutputText, 'String', myinput); ``` 這樣就可以把Edit Text方塊中輸入的文字顯示在static text方塊中 #### part 2 * 使用guide開啟新的gui * 在gui中加入兩個axes,一個pushbutton * 在pushbutton的Callback function中使用以下指令在指定的axes中繪圖 ``` t = linspace(0,2*pi,101); y1 = sin(t); axes(handles.axes1); plot(t,y1); ``` :::info 上面指令會在axes1中繪圖,若要改為axes2,則指令改為 axes(handles.axes2); ::: * 加入兩個Edit Text,分別改標籤(tag)為inputa以及inputk * 使用get指令取得inputa以及inputk兩個文字輸入框中輸入的值(因為是Edit Text,性質是String,底下指令是以str2num將其改為數值) ``` mya = str2num(get(handles.inputa,'String')); ``` 由於我們是希望以輸入的a,k畫出函數圖形,所以可以在pushbutton的Callback function中加入上面的程式碼(合併先前的繪圖程式碼) ``` mya = str2num(get(handles.inputa,'String')); t = linspace(0,2*pi,101); y1 = mya*sin(t); axes(handles.axes1); plot(t,y1); ``` 另一個做法是使用handles來傳資料。假設我們想傳的資料是myk,在函數前面你會找到一個function ``` function ex1216_OpeningFcn(hObject, eventdata, handles, varargin) ``` 因為我的檔名是ex1216,所以函數名稱是ex1216_OpeningFcn,在 ``` % Update handles structure guidata(hObject, handles); ``` 上方加入handles.myk =1; 在inputk_Callback function中加入 ``` myk_str=get(handles.inputk,'String'); handles.myk = str2num(myk_str); guidata(hObject, handles) ``` 接著在pushbutton的Callback function中加入 ``` myk = handles.myk; ``` pushbutton的Callback function裡的程式碼 mya_str = get(handles.inputa,'String'); mya = str2num(mya_str); myk = handles.myk; t = linspace(0,2*pi,101); y1 = mya*sin(myk*t); axes(handles.axes1); plot(t,y1); title(mya_str); y2 = cos(myk*t); axes(handles.axes2); ### 2021/12/20 筆記 * 把二個訊號合在一起 基本上把二個array加在一起就行了,不過要注意array長度要一樣才行。比方說我們把內建的鳥叫聲和笑聲合在一起 ``` load chirp.mat y1 =y; load laughter.mat y2 =y; ``` y1、y2的長度分別是13129、52634(另外二個音訊的Fs都是8192)。 所以用以下指令合成一個訊號(只取y2的前13129的值) ``` y3 = y1+y2(1:13129); sound(y3,Fs) ``` 要注意的是這樣直接加總得到的音訊會比原先的大聲很多,可以想辦法調整。 * 由於y1的size是13129x1(column vector),如果想把y1播放長度變成二倍,可以用以下指令 ``` y3=[y1; y1]; ``` --- ## Topic: Data Science * [kaggle](https://www.kaggle.com/c/titanic/data) * [titanic data](https://www.dropbox.com/s/zlhru9wvhb3jch5/all.zip?dl=0) * [Getting Started with Kaggle Data Science Competitions](https://blogs.mathworks.com/loren/2015/06/18/getting-started-with-kaggle-data-science-competitions/?s_eid=PSM_10705&utm_content=bufferccf05&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer) * [我的筆記本](https://hackmd.io/evMWFXDCQ66bG3fLgCkDWA) * [Supervised Learning Workflow and Algorithms](https://www.mathworks.com/help/stats/supervised-learning-machine-learning-workflow-and-algorithms.html) * [Getting Started with MATLAB](https://www.kaggle.com/c/titanic/discussion/10567) * [Boston Housing](https://www.kaggle.com/c/boston-housing) -Regression * [Classification Learner](https://www.mathworks.com/products/statistics/classification-learner.html) * [Download the MAT-file](https://www.mathworks.com/content/dam/mathworks/mathworks-dot-com/products/statistics/classification-learner/files/ClassificationLearner_Example_Datasets.mat) and double-click ClassificationLearner_Example_Datasets.mat * [UCI Iris Data Set](https://archive.ics.uci.edu/ml/datasets/Iris) * [安德森鳶尾花卉數據集 Iris flower data set wiki](https://zh.wikipedia.org/wiki/%E5%AE%89%E5%BE%B7%E6%A3%AE%E9%B8%A2%E5%B0%BE%E8%8A%B1%E5%8D%89%E6%95%B0%E6%8D%AE%E9%9B%86) * [[資料分析&機器學習] 第3.5講 : 決策樹(Decision Tree)以及隨機森林(Random Forest)介紹](https://medium.com/@yehjames/%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90-%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E7%AC%AC3-5%E8%AC%9B-%E6%B1%BA%E7%AD%96%E6%A8%B9-decision-tree-%E4%BB%A5%E5%8F%8A%E9%9A%A8%E6%A9%9F%E6%A3%AE%E6%9E%97-random-forest-%E4%BB%8B%E7%B4%B9-7079b0ddfbda) * [[第 23 天] 機器學習(3)決策樹與 k-NN 分類器](https://ithelp.ithome.com.tw/articles/10187191) * [Matlab - Select Data and Validation for Classification Problem](https://www.mathworks.com/help/stats/select-data-and-validation-for-classification-problem.html) * [Data Cleaning Techniques with the Arrhythmia Dataset](https://web.cs.dal.ca/~kallada/stat2450/practice/Practice1.pdf) * [Prediction and Classification of Cardiac Arrhythmia](http://cs229.stanford.edu/proj2014/Vasu%20Gupta,%20Sharan%20Srinivasan,%20Sneha%20Kudli,%20Prediction%20and%20Classification%20of%20Cardiac%20Arrhythmia.pdf) * [監督式學習 Supervised learning - wiki](https://zh.wikipedia.org/wiki/%E7%9B%A3%E7%9D%A3%E5%BC%8F%E5%AD%B8%E7%BF%92) * --- ## 期中考複習 [考古題](http://math.ncku.edu.tw/~mhchen/matlab/mid_10s.pdf) ### 第一題 lookfor, help, doc的使用 * 在不知道函數或指令名稱時,可以使用lookfor以關鍵字搜尋。 * 要查詢函數或指令使用方式,則是使用help或是doc查詢。 ### 改錯 * 檢查變數大小寫 * 檢查變數是否合法 * 直接把數學公式轉成程式要小心,常見問題是忘了打乘號(*)。 * 總共有五個錯誤 ### 第三題 迴圈加速以及向量式計算 ```matlab= clear all Npt=1e5; dx=(1-0)/Npt; x=linspace(0,1,Npt+1); tic for ii=1:Npt+1 y(ii)=x(ii)^2; end toc plot(x,y); ``` :::info * 原題目中的N_pt改為Npt * 迴圈前後加入tic, toc測量執行速度 ::: 1. (a)小題。這個迴圈計算由於沒有預先配置y陣列大小,所以計算速度會變慢(matlab editor右側會出現highlight提醒這個問題。只要在迴圈前宣告y陣列大小即可,可用以下幾種方式宣告: * y = x; * y = zeros(size(x)); * y = zeros(1,Npt+1); 2. (b)小題。8-10行的迴圈計算其實可以直接改成向量式計算(這個時後不必預先配置y陣列大小): * y = x.^2; [參考程式](http://math.ncku.edu.tw/~mhchen/matlab/midprob3.m) ---- ### 第四題 片段定義函數 1. (a)小題只要按照題目將函數用if-else定義即可。(考古題沒有嚴格要求要寫成函數,但是這次考試大部分題目我們會要求寫成function,同時要求輸入輸出引數順序) ```matlab= function y = mygrade(x) if x >= 50 y= 60+39*(x-50)/(94-50); elseif x>=30 y = x+5; else y =30; end end ``` :::info 注意行 5的```elseif x>=30```和題目給的 $50>x\ge 30$乍看之下不一樣,但是行 5的```elseif```是在行 3的```if x>=50```不滿足後才會進行判斷,所以結果會是一樣的。行 7的else效果也和題目的$x<30$同。 ::: [mygrade.m](http://math.ncku.edu.tw/~mhchen/matlab/mygrade.m) 2. (b)小題是將畫出前面定義的函數,要注意的是title, xlabel, ylabel以及axis的使用必須符合題目要求。 [midprob4.m](http://math.ncku.edu.tw/~mhchen/matlab/midprob4.m) 3. 參考解中```print -dpng midprob4``` 會自動將圖儲存成midprob4.png,若要儲存成jpg格式,```-dpng```改成```-djpeg```即可。 ---- ### 第五題 I/O 及計算平均 * 非常粗糙的版本 [midprob5.m](http://math.ncku.edu.tw/~mhchen/matlab/midprob5.m) * 把上面的版本中計算平均的部分改寫成函數myavg.m * [midprob5v2.m](http://math.ncku.edu.tw/~mhchen/matlab/midprob5v2.m) * [myavg.m](http://math.ncku.edu.tw/~mhchen/matlab/myavg.m) * 使用格式化輸出的版本 [midprob5v3.m](http://math.ncku.edu.tw/~mhchen/matlab/midprob5v3.m) ---- :::success 請想想有甚麼問題是用手算很困難,但是用matlab寫程式很快就可以算出來的 ::: --- ## 產生動畫 ```matlab Z = peaks; surf(Z) axis tight set(gca,'nextplot','replacechildren'); for j = 1:20 surf(sin(2*pi*j/20)*Z,Z) F(j) = getframe; end pause() %movie(F,20) % Play the movie twenty times movie2avi(F,'my_avi.avi','compression','None') ``` --- ## Project 期末專題 [期末報告說明](https://hackmd.io/fuP-M4eGSWiRSJBEbiKXwA?view) [期末報告範例](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/Matlab_Final_Project_example.pdf) ---- ### 影像處理-Droste effect * Goal: 將一圖片變形(縮小,旋轉)後再疊在原圖上 * 使用簡單的縮小mapping, 將原圖縮小 * 使用旋轉矩陣的概念, 試著將原圖片旋轉一固定角度 * 縮小以及旋轉的功能成功後, 再將新圖加在舊圖上 * 重複操作多次後可以得到Droste effect的效果 Note: 若使用 Image Processing Toolbox 裡的 imrotate, 由於旋轉圖尺寸不方正, 直接加在舊圖上會有大塊黑色區域, 可能要使用xor之類的技巧 Reference: * [Droste effect-wiki](https://en.wikipedia.org/wiki/Droste_effect) * [Droste effect (Mathematics Math21b Fall 2003 Harvard)](http://abel.math.harvard.edu/archive/21b_fall_03/droste/index1.html) Sample Code: * [rotation_triangle.m](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/rotation_triangle.m) * [img_trans.m](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/img_trans.m) * [poincare.jpg](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/poincare.jpg) ---- ### 影像處理 Mode 7 [Mode7 wiki](https://zh.wikipedia.org/wiki/Mode_7) [Mode 7 Part 1](http://www.coranac.com/tonc/text/mode7.htm) ### 影像處理 [ostagram](https://www.ostagram.me/about?locale=en) ---- ### 影像處理 油畫效果 http://angeljohnsy.blogspot.com/2011/06/oil-painting-in-matlab.html ---- ### 有限差分法解一維波方程 [有限差分法解波方程-專題內容(pdf)](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/wave_porj.pdf) {%youtube tjgiJaEpQPI %} Sample Code: * [advection.m](http://www.math.ncku.edu.tw/~mhchen/matlab11f/advection.m) * [advection_avi.m (含動畫產生)]( http://www.math.ncku.edu.tw/~mhchen/matlab11f/advection_avi.m) ---- ### Dynamical System(ODE) * 題目可以參考 Computer modeling :from sports to spaceflight-- from order to chaos by J.M.A. Danby。([Computer Modeling 目錄](http://www.math.ncku.edu.tw/~mhchen/scicomp/contents.pdf)) * 該書蒐集了不少微分方程的問題可以作為專題(Chap 6-Chap 15), 同時有區分難易程度(易 一個電腦 <---->五個電腦 難/複雜) * 兩個電腦或是一個電腦的題目難度較適合做為期末報告 * 期末報告形式可以參考[生態學之 Lokta-Volterra 模型](http://episte.math.ntu.edu.tw/applications/ap_lokta/index.html), 內容包含欲解的問題, 使用的數值方法, 模擬結果:選取一些不同的參數/初始條件, 對時間做圖, 或是相平面做圖(兩個方程式時) 參考程式: * [my_euler_sys.m](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/my_euler_sys.m) * [mypendulum.m](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/mypendulum.m) * [my_euler_LV.m (Lokta-Volterra 模型)]( http://math.ncku.edu.tw/~mhchen/iscs2016/proj/my_euler_LV.m) ---- #### 耦合振盪 * [耦合振盪說明](http://www.math.ncku.edu.tw/~mhchen/Interdiscipline/coupled_oscillators.html) * [Wave_equation From_Hooke's_law](https://en.wikipedia.org/wiki/Wave_equation#From_Hooke.27s_law) 參考程式: * [wave simulation (zip)](http://www.math.ncku.edu.tw/~mhchen/scicomp/wave_0601.zip) ---- ### 有限差分法解二維擴散反應方程 * [有限差分法解擴散反應方程-專題內容](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/RD_porj.pdf) * [Turing Patterns in Animal Coat.ppt](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/Turing_Patterns_in_Animal_Coat.ppt) * [Reaction Diffusion Systems](http://www.uni-muenster.de/Physik.AP/Purwins/RD/index-en.html) * [Reaction diffusion system (wiki)](https://en.wikipedia.org/wiki/Reaction%E2%80%93diffusion_system) Sample Code: * [ADI_RK2_RD.m](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/ADI_RK2_RD.m) * [ADI_RK2_RD_p.m (週期性邊界條件)](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/ADI_RK2_RD_p.m) ---- ### 蒙地卡羅法 ---- ### Social Simulation * [Conway Game of Life (wiki)](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) * [Conways_Game_of_Life.pptx](http://math.ncku.edu.tw/~mhchen/iscs2016/proj/Conways_Game_of_Life.pptx) * 謝林實驗 * [bias.m](http://www.math.ncku.edu.tw/~mhchen/matlab/bias.m) *[bias.jpg](http://www.math.ncku.edu.tw/~mhchen/matlab/bias.jpg) * [rndwalk.m ](http://www.math.ncku.edu.tw/~mhchen/matlab/rndwalk.m) * [random.jpg](http://www.math.ncku.edu.tw/~mhchen/matlab/random.jpg) * [friend.jpg](http://www.math.ncku.edu.tw/~mhchen/matlab/friend.jpg) ---- ### 碎型 [碎形 Fractal](http://www.atlas-zone.com/complex/fractals/index.html) ---- ### predictive-modeling https://www.mathworks.com/discovery/predictive-modeling.html?s_eid=PSM_da ---- ### 圖形介面 大部份簡單的題目, 如簡單的猜數字遊戲,Conway的生命遊戲, 畫函數圖形, 可以藉由加上適當的圖形介面作為期末專題 參考範例: [gui_example.zip](http://www.math.ncku.edu.tw/~mhchen/matlab/gui_example.zip): * gui_ex1.m: 按下按鈕後會將累計按下次數顯示在text處 myplot.m: 使用popupmenu選擇後, 按下按紐會畫出對應的函數圖形 * myplot2.m: 搭配微分方程數值解, 將解出的數值解對時間作圖同時畫出phase portrait. * num_guess.m: 在Edit Text欄位輸入數值後, 經計算後結果顯示在底下框框. 可做為猜數字遊戲的參考. 參考資料 * [MATLAB之工程應用- 第十三章 圖形介面](http://bime-matlab.blogspot.com/2006/12/blog-post_31.html) * [Creating A Graphical User Interface with MATLAB -Video](http://www.youtube.com/watch?v=D_hmws6dwgg) * [Creating Graphical User Interfaces - MathWorks](http://www.mathworks.com/help/techdoc/creating_guis/bqz79mu.html) --- ## HW 格式: * 請交截圖跟.m檔的時候要全部清掉`clear all` 同時`close all` 之後再run一次,以確保答案是對的 * 截圖請截最後結果,請直接交圖片檔 * `load`裡面請放相對路徑 11/1 fzero('cos',[0 pi]) fzero(@cos,[0 pi]) myfun = @(x,c) cos(c*x); fzero(@(x) myfun(x,1),[0 pi]) myfun2 = @(x) myfun(x,1) fzero(@(x) myfun2(x),[0 pi]) fzero(myfun2,[0 pi]) ## 2018 Fall 作業區 ### 2018/09/27課堂作業 產生一個$5\times5$的矩陣 $$ \left( \begin{array}[ccccc]\\ 0&d&0&0&0\\ -d&0&d&0&0\\ 0&-d&0&d&0\\ 0&0&-d&0&d\\ 0&0&0&-d&0\\ \end{array} \right) $$ 上述$d$值請使用input函數輸入 ```=matlab= myID = input('Student ID Number:','s') d = input('value of elements above the diagonal:') dim_N = 5; A = zeros(dim_N) Im = eye(dim_N-1) AL = A; AU = A; AL(2:dim_N,1:dim_N-1)=Im AU(1:dim_N-1,2:dim_N)=Im A = -d*AL+d*AU ``` ---- ### 2018/10/25 課堂作業 撰寫一個function,依照輸入的範圍畫出函數圖形 * 畫圖函數:sin(x2)+cosx * 繪圖範圍[a,b],為function的輸入引數 * 使用nargin等matlab內建變數判斷輸入引數是否足夠,若判斷使用者沒有輸入畫圖範圍,則採用預設範圍[0,1]。 * 請將圖形的title也設為function的輸入引數 * function plotmyfun(a,b,mytitle) * 請在command window中測試你的function,將結果截圖上傳(以學號為檔名) #### sample code ``` function plotmyfun(a,b,mytitle) %UNTITLED6 Summary of this function goes here %errmsg = nargchk(1, 2, nargin);%error(errmsg) n=1000+1; if nargin <3 mytitle = 'abcd123'; msg = 'Use default title'; warning(msg); end if nargin <2 a=0; b=1; msg = 'Use default interval [0,1]'; warning(msg); end x= linspace(a,b,n); y=sin(x.^2)+cos(x); plot(x,y) title(mytitle); end ``` ### 2018/11/29 課堂作業 * 使用zeros(512,512,3,'uint8') 指令產生一個大小為512x512的圖片陣列(使用imshow指令可以顯示代表的圖片)。 * 將陣列適當給值,可產生一個白色512x512的圖片 * figure(1)中請畫出一個大小為512x512,背景為白色,中間有一個大小為64x32藍色長方形的圖片(長條請擺直,位置大約是[224,288]x[240,272] * figure(2)請畫出一個大小為512x512,背景為白色,圖片中則是把figure(1)的長條旋轉30度(π/6)的結果 * 使用title指令在figure(1)中顯示你的學號姓名 * 將figure(1)及figure(2)截圖上傳(一張圖同時包含figure(1)及figure(2)) * NOTE: 若來不及完成figure(2)旋轉部分,請至少完成figure(1),figure(2)改成在圖上其他區域畫一個紅色長方形。 ``` clear all close all A = zeros(512,512,3,'uint8'); A(:,:,:)=255; %figure(1), imshow(A) A(224:288,240:272,1:2) = 0; %figure(2), imshow(A) % A(1:16,11:33,1:2) = 0; % figure(1), imshow(A) B = zeros(512,512,3,'uint8'); B(:,:,:)=255; ic =256; jc =256; theta = pi/6; for in = 256-64:256+64 for jn = 256-64:256+64 iold = round((cos(theta)*(in-ic)+sin(theta)*(jn-jc))+ic); jold = round((-sin(theta)*(in-ic)+cos(theta)*(jn-jc))+jc); B(in,jn,:) = A(iold,jold,:); end end figure(2), imshow(B) C = zeros(512,512,3,'uint8'); C(:,:,:)=255; for in = 224:288 for jn = 240:272 inew = round((cos(theta)*(in-ic)-sin(theta)*(jn-jc))+ic); jnew = round((sin(theta)*(in-ic)+cos(theta)*(jn-jc))+jc); C(inew,jnew,:) = A(in,jn,:); end end figure(3), imshow(C) ``` ## 2018 Homework 暫存區 ### HW2 說明&提示: 0. 讀取 `data.mat` 1. 字串合併:利用 `strcat()` 把字串與 `name` 變數合併成新的字串 ---- 2. 矩陣對角化:在紙上計算一個矩陣的高次方時,通常不好算且容易算錯。如果我們找到了可逆的 $Q$ 矩陣,使得 $Q^{-1}AQ=D$ 是對角矩陣,則稱為 $A$ 是可對角化的。此時 $A=QDQ^{-1}$,透過 $A^{k}=(QDQ^{-1})^k=QD^kQ^{-1}$ 便可以很容易地算出 $A^k$。而對角矩陣 $D$ 上的元素為矩陣 $A$ 的特徵值。 <br><br>(a)小題即是提供 $Q$ 與 $A$ 矩陣,驗證 $Q^{-1}A^kQ=D^k$<br>(b)小題利用第一堂課提到的`eig()` 函數來計算矩陣 $A$ 的特徵值。至於如何把他放成矩陣的樣子,請使用 `help eig` 查詢。<br><br>[WIKI : 可對角化矩陣](https://zh.wikipedia.org/wiki/可对角化矩阵)<br>[WIKI : 特徵向量](https://zh.wikipedia.org/wiki/特征向量) ---- <br>(同學反應有些功能系上MATLAB版本無法使用,不過助教的電腦是最新版本,同學可以使用新版指令沒關係!)<br><br> ---- 3. 將線性方程組寫成 $PX=Q$ 的樣子,當 $P$ 存在反矩陣,可以利用兩邊同乘 $P^{-1}$ 來得到 $X=P^{-1}Q$ <br>(Q變數會跟第二題衝突,同學可以自行更換變數)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully