Chapter 2: Exercises

Part 1

  1. 請在 MATLAB 直接輸入下列常數,看它們的值是多少:
    1. i
    2. j
    3. eps
    4. inf
    5. nan
    6. pi
    7. realmax
    8. realmin
  2. 請使用 lookfor 指令,找出具有下列功能的 MATLAB 指令。(每一項只需找出一個 相關度最高的 MATLAB 指令。)
    1. 找出矩陣的大小(即行維度和列維度)
    2. 改變矩陣的大小(例如將 4×6 的矩陣改成 12×2)
    3. 將矩陣左右翻轉(Left-right flip)
    4. 將矩陣上下翻轉(Up-down flip)
    5. 找出矩陣每一直行的最大值
    6. 對矩陣的每一直行進行排序
    7. 矩陣的旋轉(Rotate)
    8. 反矩陣(Inverse matrix)的計算
    9. 求矩陣的 rank
    10. 計算矩陣的 reduced row echelon form
    11. 計算矩陣的 null space
    12. 計算矩陣的固有值(Eigenvalues)與固有向量(Eigenvectors)
    13. 計算矩陣的 QR 分解(QR Decomposition)
    14. 計算矩陣的 LU 分解(LU Decomposition)
    15. 計算矩陣的奇異值分解(Singular Value Decomposition)
    16. 對向量進行快速傅立葉轉換(Fast Fourier Transform)
    17. 直角座標轉成極座標
    18. 極座標轉成直角座標
  3. (*)When does n! explodes: Write a MATLAB script to find the minimal value of n such that n!>realmax. What is the value of n? What is the value of (n-1)! ?
  4. 寫一個 MATLAB 小程式 findN01.m,求出最小的 n 值,使得 n! > realmax。請問 n 的值是多少?此時 (n-1)! 的值又是多少?

    02-初探MATLAB/findN01.mmaxN = 1000; for n=1:maxN value = prod(1:n); if value>realmax break; end end fprintf('n = %d\n', n); fprintf('(n-1)! = %d\n', prod(1:n-1));

  5. MATLAB 的 sqrt 指令可對任一數值進行開平方的運算。用此指令求出下列各數的平方根,並驗算之:
    1. p
    2. 2*i
    3. -5+12*i
    其中 i 是單位虛數。
  6. (*)Basic function for both scalar and vector inputs: Write a MATLAB function to evaluate the following expression:
    0.5*exp(x/3)-x*x*sin(x)
    where x is the input and y is the output of the function. You function should be able to handle both the situations when x is a scalar or a vector. Please use the following code segment to plot the expression: x=0:0.1:10; plot(x, myFun01(x));
  7. 寫一個 MATLAB 函數 myFun01.m 來計算下列方程式:
    y = 0.5*exp(x/3)-x*x*sin(x)
    其中 x 是函數的輸入,y 是函數的輸出。你的函數必須能夠處理當 x 是純量或是向量的兩種情況。此外,請利用下述兩列程式碼來畫出此函數的圖形: x=0:0.1:10; plot(x, myFun01(x));

    02-初探MATLAB/myFun01.mfunction y = myFun(x) y = 0.5*exp(x/3)-x.*x.*sin(x);

    1. 寫一個 MATLAB 函數 piFun01.m 來計算下列級數:
      f(n) = 4*(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...)
      其中 n 為函數的輸入,代表上述級數的項數,級數和 f(n) 則是函數的輸出。
    2. 使用 tic 和 toc 指令來測量 piFun01(100000) 的計算時間。如果你不知道如何使用這兩個指令,請使用 help tic 及 help toc 來查出它們的用法。我的舊電腦是 Pentium 450MHz,所得的計算時間約為 2 秒。請說明你的電腦規格以及其計算時間。

    02-初探MATLAB/piFun01.mfunction out = piFun(n) % piFun: Use sum of sequence to approximate pi % Roger Jang, 20030726 total=0; for i=1:n item = (-1)^(i+1)/(2*i-1); total = total+item; end out = 4*total;

  8. (**) Function for computing the Fibonacci number:
    1. Write a recursive function fibo.m to compute the Fibonacci sequence, which is defined as follows:
      fibo(n+2)=fibo(n+1)+fibo(n)
      s The initial conditions are fibo(1)=0, fibo(2)=1.
    2. What is the value returned by fibo(25)?
    3. Please use the commands tic and toc to measure the computation time of fibo(25). If you don't know how to use tic and toc, please try "help tic" and "help toc" in MATLAB command window. Please state the specs of your computer and the computation time of fibo(25).
    4. If you have taken Discrete Mathematics, you should already known that the n-th term of a Fibonacci sequence can be expressed as
      fibo(n)={[(1+a)/2]^(n-1)-[(1-a)/2]^(n-1)}/a
      where a is the square root of 5. Write a non-recursive function fibo2.m to compute Fibonacci sequence according to the above expression.
    5. What is the value of fibo2(25)? Is it the same as fibo(25)?
    6. Compare the computation time of fibo2(25) and fibo(25).
    7. Please list the advantages and disadvantages of fibo.m and fibo2.m.
    1. 寫一個 MATLAB 的遞迴函數 fibo.m 來計算 Fibonacci 數列,其定義如下:
      fibo(n+2) = fibo(n+1)+fibo(n)
      此數列的啟始條件如下:
      fibo(1) = 0, fibo(2) = 1.
    2. fibo(25) 的回傳值是多少?
    3. 使用 tic 和 toc 指令來測量 fibo(25) 的計算時間。如果你不知道如何使用這兩個指令,請使用 help tic 及 help toc 來查出它們的用法。我的電腦是 Pentium 2GHz,所得的計算時間約為 3.35 秒。請說明你的電腦規格以及其計算時間。
    4. 如果你修過離散數學,就會知道 Fibonacci 數列的第 n 項可以直接表示成
      fibo(n)={[(1+a)/2]^(n-1)-[(1-a)/2]^(n-1)}/a
      其中 a 是 5 的平方根。寫利用上式一個 MATLAB 的非遞迴函數 fibo2.m 來計算 Fibonacci 數列。
    5. fibo2(25) 的值為何?是否和 fibo(25) 相同?
    6. 請計算 fibo2(25) 的計算時間,並和 fibo(25) 比較。
    7. 請比較並說明使用 fibo.m 和 fibo2.m 來計算 Fibonacci 數列的優缺點。

    02-初探MATLAB/fibo.mfunction out = fibo(n) % fibo: Fibonacci number % Roger Jang, 20030726 if n==1 out=0; return; elseif n==2 out=1; return; else out=fibo(n-1)+fibo(n-2); end

    02-初探MATLAB/fibo2.mfunction out = fibo(n) % fibo: Fibonacci number using an analytic expression % Roger Jang, 20030726 r1=(1+sqrt(5))/2; r2=(1-sqrt(5))/2; out=(r1^(n-1)-r2^(n-1))/sqrt(5);

  9. (**) Find the minimum of a matrix:
    1. Write a MATLAB function minxy.m which can find the minimal element in a 2-dimensional matrix:
      [minValue, minIndex] = minxy(matrix)
      where matrix is a 2-d matrix, minValue is the minimal element of the input matrix, and minIndex is an integer vector of length 2 indicating the indices of the minimal element. (In other words, matrix(minIndex(1), minIndex(2)) is equal to minValue.)
    2. Test you program by typing the following statement in MATLAB command window:
      [minValue, minIndex]=minxy(magic(20))
      What are the returned values of minValue and minIndex?
    1. 請寫一個函數 minxy.m,其功能是由一個二維矩陣中找出小元素,用法如下:
      [minValue, minIndex] = minxy(matrix)
      其中 matrix 是一個二維矩陣,minValue 則是其元素的最小值,而 minIndex 是一個長度為 2 的正整數向量,代表最小值的索引。(換句話說,matrix(minIndex(1), minIndex(2)) 的值即是 minValue。)
    2. 請測試 [minValue, minIndex] = minxy(magic(20)) 所傳回來的 minValue 和 minIndex 各是多少?

    Hint
    請盡量使用 min 指令。

    02-初探MATLAB/minxy.mfunction [minValue, minIndex] = minxy(matrix) %MINXY Minimum of a 2D matrix % Usage: [minValue, minIndex] = minxy(A) % minValue: the minimum of the matrix A % minIndex: the 2D index of minValue in A % Roger Jang, 20010219 [columnMin, columnMinIndex] = min(matrix); [minValue, tmp] = min(columnMin); minIndex = [columnMinIndex(tmp) tmp];

Part 2

  1. Facts about MATLAB: Please answer the following short questions:
    1. What is the MATLAB command to display the version of the MATLAB you are using?
    2. What is the MATLAB command to test the speed of your computer when executing MATLAB?
    3. What are the MATLAB commands to seek for online help?
    4. What is the MATLAB command to display the search path?
    5. What is the MATLAB command to find the path of a command?
    6. How do you add a folder to the search path of MATLAB?
    7. How do you delete a folder from the search path of MATLAB?
    8. What is the default data type of variables in MATLAB?
    9. How do you create comments in a MATLAB program?
  2. Create a magic matrix: Create a 5-by-5 magic matrix by hand. (You don't need to explain how you derive it.)
  3. Vector indexing: Given two row vectors x and y of the same length, write a one-line MATLAB statement to achieve the following goals:
    1. Change element 3 by multiplying it by 5.
    2. Append an element of value 5.
    3. Delete element 2.
    4. Concatenate x and y.
    5. Stack x and y.
  4. Matrix indexing: Given a 5-by-5 matrix matrix A, write a one-line MATLAB statement to achieve the following goals:
    1. Delete row 2 of A.
    2. Delete rows 2 and 4 of A.
    3. Delete column 3 of A.
    4. Delete columns 3 and 5 of A.
    5. Change row 4 of A by multiplying it by 5.
    6. Change columns 1 and 4 of A by multiplying it by 3.
    7. Switch columns 1 and 3 of A.
    8. Switch columns 1 and 3, and rows 3 and 5, of A.
    9. Replace column 3 by row 4.
    10. Replace rows 2 and 4 by columns 1 and 5.
    11. Assign a logical variable Y to verify sum of each column of A is equal to 65.
    12. Assign a logical variable Y to verify sum of each row of A is equal to 65.
    13. Assign a logical variable Y to verify the diagonal sum of A is equal to 65.
    14. Assign a logical variable Y to verify the anti-diagonal sum of A is equal to 65.
    15. Assign B to be columns 4, 2, and 5 of A.
    16. Assign B to be the second to fourth elements of column 4 of A.
    17. Assign B to be the concatenation of the third to fifth elements of column 4, and the first to fourth elements of column 5, of A.
    18. Assign B to be the diagonal vector of A, without using "diag" command.
    19. Assign B to be diag(A, -1), without using "diag" command. (This is, [23 6 19 2] for A=magic(5).)
    20. Assign B to be diag(A, 1), without using "diag" command. (This is, [24 7 20 3] for A=magic(5).)
    21. Put A at the upper left corner of a zero matrix of 7 by 7.
    22. Put 5:14 into the first two columns of A.
    23. Put 5:14 into the last two columns of A.
  5. Simple indexing: What is the value of the variable d after executing the following script: a = [10 20;30 40]; b = [10 30;30 30]; c = a>b; d = a(c);
  6. Simple math on matrices: Given a matrix A, write a one-line MATLAB statement to achieve the following goals:
    1. Find the max. of each row.
    2. Find the min. of each column.
    3. Sort each row.
    4. Sort each column in descending order.
    5. Find the max. of min. of each column.
    6. Find the max. of min. of each row.
  7. Rotation and reflection: Given a n-vertex polygon denoted as a complex vector of n elements z=[z1, z2, ..., zn]. Use a few MATLAB statements to compute the coordinates of the polygon after the following operations.
    1. Rotate p/6 with respect to the origin.
    2. Rotate p/6 with respect to its center (which is the mean of all the vertices).
    3. Reflection along a line q=p/3.
    4. Flip the polygon along a straight of slope 1/2 which passes the polygon's center.
    5. What is the rotation matrix? What is the reflection matrix?
  8. Ackermann's function: 請使用 MATLAB 來寫一個遞迴函數以計算下列 Ackerman's function:
    A(m, n) =
    n+1, if m=0
    A(m-1,1), if n=
    A(m-1, A(m,n-1)), otherwise
  9. 矩陣加法之延伸: 請寫一個函數 myAdd.m,其功能是將兩個維度不同的向量或矩陣相加,用法如下:
    output = myAdd(a, b)
    其中 a 和 b 都是二維的矩陣,但他們的維度可能不同,因此無法直接進行一般的矩陣加法運算,而此函數會在執行加法之前,先將這兩個矩陣經由「補零」(個數越少越好)來擴展成維度相同的矩陣,然後再進行一般矩陣加法運算。例如,當 a = [1 2 3; 4 5 6],b = [5; 2],此時 myAdd(a, b) 所傳回來的結果是 [6 2 3; 6 5 6]。另,此函數不支援純量展開(Scalar Expansion),所以 myAdd([1, 1], 2)應該傳回 [3, 1],而非 [3, 3]。

    (English version) Write a function myAdd.m which can add two matrices with different dimensions, with the following usage:

    output = myAdd(a, b)
    where a and b are given 2D matrices, with perhaps different dimensions. Hence, it is not always possible to perform the common matrix addition. As an extension, myAdd can extend the given matrices to have the same dimensions (with minimum padded zeros), then add them to create the final output. For instance, when a = [1 2 3; 4 5 6] and b = [5; 2], myAdd(a, b) should return [6 2 3; 6 5 6]. Moreover, the function do not support scalar expansion, so myAdd([1, 1], 2)returns [3, 1] instead of [3, 3].
  10. 矩陣乘法之延伸: 請寫一個函數 myMultiply.m,其功能是將兩個維度「不搭嘎」(Mismatch)的矩陣相乘,用法如下:
    output = myMultiply(a, b)
    其中 a 和 b 都限定是一維的向量或是二維的矩陣,但他們的維度可能「不搭嘎」,因此無法直接進行一般的矩陣乘法運算。,而此函數會在執行乘法之前,先將這兩個矩陣經由「補 1」來擴展成「搭嘎」的矩陣,然後再進行一般矩陣成法運算。例如,當 a = [2 2 2; 3 3 3],b = [1; 2; 3; 4],此時 myMultiply(a, b) 會將 a 補成 [2 2 2 1; 3 3 3 1],然後在進行矩陣乘法運算,所傳回來的結果是 [16; 22]。另,此函數不支援純量和矩陣之間的簡易乘法,所以 myMultiply([1, 1], 2)應該傳回 [1, 1]*[2; 1] = 3。
  11. Derivation of the Euler's number: This exercise is about the derivation of the Euler's number which is the base of the natural logarithm. The Euler's number is defined as follows: $$e = \lim_{n\rightarrow \infty} \left(1+\frac{1}{n}\right)^n$$
    1. Give the formula of $(x+y)^n$ based on the binomial theorem.
    2. Prove that e can be reformulated as follows: $$e = \frac{1}{0!} + \frac{1}{1!} + \frac{1}{2!} + \frac{1}{3!} + \cdots$$
  12. Approximation of ln(1+r): This exercise is about the approximation of $ln(1+r)$.
    1. Give the formula of the Taylor series expansion of a general well-behaved function $f(x)$ at $x=a$.
    2. Use the expansion to explain why $ln(1+r)$ can be approximated by $r$ as $r$ is close to zero.
  13. Computing the Euler's number (part 1): Let's assume the Euler's number e = 2.71828182845904523536.
    1. Write a function to approximate the Euler's number by the following formula:
      fun1(n) = (1+1/n)n
    2. Plot the function as n goes from 1 to 1000.
    3. Write a script to determine the smallest value of n such that |fun1(n) - e| < 10-5 ?
  14. Computing the Euler's number (part 2): Let's assume the Euler's number e = 2.71828182845904523536.
    1. Write a function to approximate the Euler's number by the following formula:
      fun2(n) = 1/0! + 1/1! + 1/2! + 1/3! + ... + 1/n!
    2. Plot the function as n goes from 1 to 100.
    3. Write a script to determine the smallest value of n such that |fun2(n) - e| < 10-5 ?
  15. Rule of 70:
    1. Please explain what "Rule of 70" (also known as "Rule of 72" or "Rule of 69") is.
    2. Please derive the exact formula for the above rule, assuming $ln(1+r) = r$ when $r$ is close to zero.
  16. Computing for rule of 70: Please refer to the wiki page of Rule of 72 for this and all the following exercises.
    1. Write a MATLAB program to plot the first table in the above wiki page, where x-axis is the rate from 0% to 70%, and y-axis is the no. of years for doubling the investment. The plot should have 6 curves, corresponding to columns 2 to 7 of the table.
    2. Write a MATLAB program to plot the deviation from the actual years of doubling the investment.
  17. Comparison of compounding at various frequencies: Please write a MATLAB script to generate the comparison plot shown here. (Hint: use "stairs" to plot a function in a stairwise manner.)
  18. 租金終值: 假設你是社會新鮮人,在台北市找到一份工作,同時租了一個套房,每個月一萬元。假設銀行存款年利率是3%,請問五年後,房租總值是多少?十年後呢?
  19. 銀行貸款月付額: 為了創業,你跟銀行申請青年創業貸款100萬,銀行放款年利率是3%,分20年每月定額還清。請問每個月要付多少錢?
  20. 房貸月付額: 為了買房子,你跟銀行貸款500萬,20年還清。假設寬限期兩年,放款年利率3%,請問在寬限期間,你每個月要付多少錢?寬限期後呢?
  21. 買房投資精算: 請寫一個MATLAB腳本,進行下列運算。(Hint: You can use the functions "loan" and "saving" in the Utility Toolbox.)

    如果你你有自備款100萬元,打算在台北市買了一間500萬的套房,剩餘400萬元要向銀行貸款,分20年本利攤還。

    1. 假設銀行放款年利率是3%,請問每個月要付銀行多少錢?假設我們採用「本息平均攤還」,且沒有寬限期。
    2. 假設台北市的房子以每年7%的速度增值,請問二十年後你把房子賣掉,可以賺多少錢?(Hint: 先計算房子20年後的終值 x,再計算20年後你付給銀行的所有房貸的終值 y,以及將自備款100萬放在銀行20年後的終值 z,你20年後賺到的錢就會等於 x - y - z。)
    3. 承上小題,轉成現值是多少錢?(假設你20年後所賺到的錢是 v,那麼它的現值 u,就會滿足「將 u 存放銀行20年後,得到的本利和為 v」。)
    4. 重複 (b) 小題,但假設房子每個月還可以收取租金一萬元。(Hint: 假設你每個月的房貸是 x 元,有了房租,你只要付 (x-10000) 元。)
    (在解上述問題時,我們不考慮通貨膨脹等其它因素,並假設銀行的存款利率只有1.38%。)

    Hint: My result for your reference...

    以下計算以萬元為單位 Monthly payment = 2.21839 Without rent income: Final value of the house = 2019.37 Final value of the monthly payments = 612.737 Final value of the down payment = 131.764 Final earning = 2019.37-612.737-131.764 = 1274.87 Initial earning = 967.54 With rent income: Final value of the monthly payments = 336.529 Final earning = 2019.37-336.529-131.764 = 1551.08 Initial earning = 1177.16
  22. Function for computing IRR: Write a function to compute the IRR (Internal Rate of Return) of a given investment plan. A basic example for yearly compounding and yearly cash flow is shown next:

    02-初探MATLAB/irrFind.mfunction r=irrFind(cashFlowVec, x0) r=fzero(@npvCompute, x0); function npv=npvCompute(x) n=length(cashFlowVec); npv=sum(cashFlowVec./((1+x).^(0:n-1))); % Yearly compounding end end

The new function has the following usage:
irr=myIrrFind(cashFlowVec, x0, 'timeUnit4cashFlow', 'timeUnit4compounding');
where Note that if timeUnit4cashFlow is not 12 and timeUnit4compounding is 'year', the function should return nan.
MATLAB程式設計:入門篇