introduction to matlab programming with applicationsd00922011/matlab/237/...i in algorithm analysis,...

34
Repetition Structures I As a rule of thumb, if a section of code is repeated more than three times, it is a good candidate for a repetition structure. I Repetition structures are often called loops. I All loops consist of 5 basic parts: I A parameter to be used in determining whether or not to end the loop. I Initialization of this parameter. I A way to change the parameter each time through the loop. 1 I A comparison, using the parameter, to a criterion used to decide when to end the loop. I Calculations to do inside the loop. 1 If not, then an infinite loop, that is, a loop never stops. 1 / 34

Upload: lydat

Post on 14-May-2018

220 views

Category:

Documents


1 download

TRANSCRIPT

Repetition Structures

I As a rule of thumb, if a section of code is repeated more thanthree times, it is a good candidate for a repetition structure.

I Repetition structures are often called loops.I All loops consist of 5 basic parts:

I A parameter to be used in determining whether or not to endthe loop.

I Initialization of this parameter.I A way to change the parameter each time through the loop.1

I A comparison, using the parameter, to a criterion used todecide when to end the loop.

I Calculations to do inside the loop.

1If not, then an infinite loop, that is, a loop never stops.

1 / 34

I MATLAB supports two different types of loops: the for loopand the while loop.

I Two additional commands, break and continue, can be usedto create a third type of loop, called a midpoint break loop.

2 / 34

for Loops

I for loop is the easiest choice when you know how many timesyou need to repeat the loop.

for(index = array)statements

end

3 / 34

4 / 34

Example: for

clear all ;clc% mainfor i=[1 3 5] % Can be a string. (Try.)

iend

clear all ;clc% mainfor i=0:1:10

iend

5 / 34

while Loops

I While loops are the easiest choice when you need to keeprepeating the instructions until a criterion which is written inlogical expression is met.

while(criterion)statements

end

6 / 34

Example: while

I Write a program to determine the number of terms requiredfor the sum of the series 5k2 − 2k, k ∈ N to exceed 104.What is the sum for this many terms?

clear all ;clc% mainsol=0;k=1;while sol < 1e4

sol=sol+5∗kˆ2−2∗k;k=k+1

endk

7 / 34

8 / 34

Midpoint break Loops

I Midpoint break loops are useful for situations where thecommands in the loop must be executed at least once, butwhere the decision to exit the loop is based on some criterion.

I A break statement will cause termination of the smallestenclosing while or for loop.

9 / 34

Example: break

clear all ;clc% mainwhile(1) % infinite loop

a=input(’Enter a value greater than 0 or −1 to exit: ’ );if (a==−1)

fprintf ( ’Bye.\n’ );break

elseif a>0fprintf ( ’ log10(%d) = %g\n’, a, log10(a));

elsedisp( ’Only positive numbers!’)

endend

10 / 34

Example: How many levels can one break break?2

clear all ;clc% maini=0;while ( i<10)

for k=0:1:4for kk=0:1:2

if i==4fprintf ( ’−−−−−−−− %d\n’,i);break

endend

endi=i+1;

end

2Thanks to a lively class discussion (MATLAB-237) on April 19, 2014.11 / 34

Basic Plotting

I A simple example shows how to plot in MATLAB.

clear all ;clc ;% mainx=linspace(0,4∗pi,1e2);y=sin(x); % vectorization in MATLABplot(x,y, ’∗’ );

I We will revisit basic plotting soon.

12 / 34

Exercise

I Gauss’ teacher asked him to add up all of the numbers 1through 100 when he was 9.

I Question:∑100

i=1 i =?

clear all ;clcx=0;for i=1:1:100

x=x+i;endx

13 / 34

Figure : Carl Friedrich Gauss, 1777–1855

14 / 34

Extension

I 把100改成使用者輸入一個正整數n,觀察1 · · · n的級數和的趨勢。

I Please plot∑j

i=1 i for all j ∈ 1, · · · , n.I Hint: You may need a nested for loop of two levels.

15 / 34

Solution 1

clear all ;clc% mainn=input(’Please enter an positive integer : ’ );y=zeros(n,1); % Initialize an empty array of n cellsfor i=1:1:n

x=0; % Initialize a temp variablefor j=1:1:i % starts from 1 to i

x=x+j;endy( i)=x; % Collect the sum for each i

endplot(1:n,y, ’∗: ’ );

16 / 34

Solution 2

clear all ;clc% mainn=input(’Please enter an positive integer : ’ );y=zeros(n,1); % Initialize an empty array of n cellsfor i=1:1:n

y( i)=x+i;endplot(1:n,y, ’∗: ’ );

17 / 34

Analysis of Algorithms

I 一個問題除了找出一個正確的演算法以外,更重要的問題是,還有沒有更有效率的演算法? (Why?)

I In algorithm analysis, we focus on the growth rate of therunning time or space requirement as a function of the inputsize n, denoted by f (n).

18 / 34

O-notation

I 讀作big O。

I In math, O-notation describes the limiting behavior of afunction when the argument tends towards a particular valueor infinity, usually in terms of simpler functions.

I Definition (O-notation) f (x) = O(g(x)) as x →∞ if andonly if there is a positive constant c and a real number x0such that

|f (x)| ≤ c |g(x)| ∀x ≥ x0. (1)

19 / 34

I For example, the function 8n2 − 3n + 4 is O(n2).

20 / 34

I O-notation is used to classify algorithms by how they respondto changes in input size.3

I Time ComplexityI Space Complexity

I In short, O-notation describes the asymptotic4 upper boundof the algorithm.

I Upper bound: the worst case we can expect.

I More details can be found in textbooks for Data Structures orAlgorithms5.

3Actually, there are Θ, θ, o,Ω, and ω which classify algorithms.4The asymptotic sense is that the input size n grows toward infinity.5Introduction to Algorithms, Cormen, 3/e

21 / 34

22 / 34

Growth Rates for 7 Fundamental Functions

23 / 34

Solution 1 vs Solution 2

I Time ComplexityI Solution 1 runs in O(n2) while Solution 2 runs in O(n).I So, we can say that Solution 2 is more efficient6 than Solution

1.

I Space ComplexityI Solution 1 and Solution 2 both have O(n).

6Faster.

24 / 34

Closed-Form Formula

I It’s well-known that∑n

i=1 i =n(n + 1)

2.

I Moreover, it is also known that

I∑n

i=1 i2 =

n(n + 1)(2n + 1)

6, and

I∑n

i=1 i3 = (

n(n + 1)

2)2.

I How about∑n

i=1 ik for any real number k?

25 / 34

Why Numerical Methods?

I Numerical methods open a window for many complicatedproblems, even if the correctness of the numerical solutionremains a big problem itself.

I Simulation techniques significantly reduce the cost both inindustry and science.

I 注意:擁有解析解的問題太少,多的是沒有解析解的問題。

“All science is dominated by the idea of approximation.”– Bertrand Russell (1872-1970)

26 / 34

Exercise: 定存問題

I 每年年初定存一萬元新台幣,年利率r = 10%,採一年計息一次(annual compounding),第十年結束後本利和為7?

I 175, 311.670611 NTD.

7本金共100, 000 NTD。

27 / 34

28 / 34

Solution 1

clear all ;clc ;% mainformat long gsum=1e4;r=0.1; % Annual interest ratefor i=1:1:10

if i==10sum=sum∗(1+r)

elsesum=1e4+sum∗(1+r);

endend

29 / 34

Title

I Time complexity: O(n)

I Space complexity: O(1)

I It is similar to Horner’s method.

30 / 34

Solution 2

clear all ;clc ;% mainformat long gsum=0;r=0.1;i=1;while ( i<11)

sum=sum+(1+r)ˆi;i=i+1;

endsum=1e4∗sum

I Time complexity: O(n)I Space complexity: O(1)

31 / 34

Solution 3

clear all ;clc ;% mainformat long gx=1e4;r=0.1;n=10;sum=x∗(1+r)∗((1+r)ˆn−1)/r

I Time complexity: O(1) (Why?)

I Space complexity: O(1)I Remarks:

I Pros: Fastest and compact code.I Cons: Less flexible.

32 / 34

Extension: Floating Interest Rate

I Instead of constant interest rate, the floating interest rates aregiven by

r = 0.1 : −0.01 : 0.01.

Then determine the compound amount of the previousexample.

I 124,193.45782882 NTD

33 / 34

Solution

clear all ;clc ;% mainformat long gsum=0;r=linspace (0.1,0.01,10);i=1;while ( i<11)

sum=sum+(1+r(i))ˆi;i=i+1;

endsum=1e4∗sum

34 / 34