chapter 8 loops while loop syntax while ;... end;

26
Chapter 8 Loops while loop syntax while <condition> <statement>; <statement>; . . . end;

Post on 20-Dec-2015

246 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 8 Loops while loop syntax while ;... end;

Chapter 8 Loops

while loop syntax

while <condition>

<statement>; <statement>;

. . .

end;

Page 2: Chapter 8 Loops while loop syntax while ;... end;

Example 1: Given an array A in which A(1:k-1) is sorted. Write a function to insert A(k) in its correct place among A(1:k-1) so that A(1:k) is sorted.

function out = insert(A, k) % assume k > 1 and A(1:k-1)is sorted temp = A(k); j = k-1; while (j > 0) if A(j) > temp A(j+1) = A(j); j = j – 1; else break; end; A(j+1) = temp; out = A;

Page 3: Chapter 8 Loops while loop syntax while ;... end;

Insertion sorting

function B = insertionSort(A) j = 2; while (j <= length(A)) B = insert(A, j); j = j + 1; end; >> B = [ -18 8 -4 13 24 2 5 37 3 12 24 81 45];

>> B = insertionSort(B);>> B

B =

-4 2 5 8 13 24 37 -18 3 12 24 45 81

Page 4: Chapter 8 Loops while loop syntax while ;... end;

for loop syntax

for j = 1:20

<statement sequence>

end

Page 5: Chapter 8 Loops while loop syntax while ;... end;

Simulating the outcome of a probability game

Players A and B play the following game. A fair coin is tossed until one of the two patterns HTH or THT occurs. If the first pattern (HTH) occurs, A wins else B wins.

What is the probability that A wins the game?

There are two ways to solve this problem:

• Use Markov chain (can find the answer exactly)

• Simulation (simulate the game a large number of times and record the number of wins by each player)

Page 6: Chapter 8 Loops while loop syntax while ;... end;

Simulation based solution

Outer loop: repeat the game a large number of times, say 100000.

Inner loop: each iteration represents one game.

Outline of solution: countA = 0; countB = 0; for j = 1: 100000 while the game is not over toss coin once; update the last three bits; end; update the winner count; end;

Page 7: Chapter 8 Loops while loop syntax while ;... end;

We will write three functions:

toss() produces ‘T’ or ‘H’ with probability 0.5

tossgame() produces ‘A’ (‘B’) if A (B) is the winner of one randomly simulated game

repeatTossGame(n) repeat the tossgame n times, find a = the number of times A wins and output the ratio a/n

Page 8: Chapter 8 Loops while loop syntax while ;... end;

Project – entropy computation

The concept of entropy is fundamental to information and coding theory – which deals with efficient ways to add redundancy to the data so that the receiver can recover the message even if some of data is corrupted by the channel.

Information theory was developed by Claude Shannon.

Watch movie about Shannon in UCTV.http://www.uctv.tv/search-details.aspx?showID=6090

Page 9: Chapter 8 Loops while loop syntax while ;... end;

probability distribution of individual letters

The basic idea of information theory is that if the input has less randomness, it can be more easily predicted and hence it can be compressed to greater degree.

Suppose there are k distinct symbols in a text.

Let P(j-th symbol) = pj.

Entropy is defined as:

E = – jpj log pj

Goal is to compute the entropy of a given text.

Page 10: Chapter 8 Loops while loop syntax while ;... end;

Example: Given a three-letter alphabet containing E, Z and _ with frequencies as follows:

E Z _

0.5 0.25 0.25

Entropy is given by:

E = -0.5 log2 0.5 – 0.25 log2 0.25 – 0.25 log2 0.25

Using matlab, we can compute E as:

>> p = [0.5 0.25 0.25]

p =

0.5000 0.2500 0.2500

>> -sum(p.*log2(p))

ans =

1.5000

>>

Page 11: Chapter 8 Loops while loop syntax while ;... end;

Project: Write a program in Matlab that computes the entropy of English.

•Step 1: collect a corpus of text. count the frequency of letters for the corpus.

• text will be stored in multiple files• program should calculate the frequency of letters across all the files.

•Step 2: compute entropy from the frequency table.

Page 12: Chapter 8 Loops while loop syntax while ;... end;

Recursive functions

Before we conclude this chapter, we will discuss recursive functions, those that can call themselves.

We have examples of functions that call other functions, e.g. insertionsort calling insert etc.

If f(n) is defined in terms of f(n – 1), as for example, in the case of factorial, why not let f call itself?

n! = n x (n – 1)!

Or in matlab:

fact(n) = n .* fact(n – 1)

Page 13: Chapter 8 Loops while loop syntax while ;... end;

Rules for recursive functions

1. there should be exit from recursion. (i.e., there should be some conditional branch path in which there is no recursive call). Such cases are called the base cases.

2. recursive calls should make towards base case (usually by calling itself with smaller input values).

3. To understand what a recursive function does, create a table of its outputs for input = 1, 2, 3, … etc. Then study the pattern.

Page 14: Chapter 8 Loops while loop syntax while ;... end;

Example 1: Write a recursive function to compute n! function out = fact(n)

if n <= 1 out = 1;else out = n .* fact(n-1);end;

Page 15: Chapter 8 Loops while loop syntax while ;... end;

Example 2: Write a recursive function in Matlab to perform binary search.

Assume array A is sorted in ascending order.

Search(A, low, high, x) will return the largest t such that A(t) <= x.

Pre-condition: A(low) <= x <= A(high)

Thus low <= t <= high.

Initially, low = 1, high = size(A)

Page 16: Chapter 8 Loops while loop syntax while ;... end;

Recursive binary search programfunction out = search(A, low, high, x) % returns the largest t s.t. A(t) <= x where low <= t <= high % A is assumed to be sorted if high - low == 1 if A(high) == x out = high; else out = low; end; else mid = floor((low + high)/2); if A(mid) == x out = mid; elseif A(mid) < x out = search(A, mid + 1, high, x); else out = search(A, low, mid - 1, x); end; end;

Page 17: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.1.

>> repeat([2 3; 3 1; 4 2]

ans = [ 2 2 2 3 4 4 ]

Page 18: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.1.

>> repeat([2 3; 3 1; 4 2]

ans = [ 2 2 2 3 4 4 ]

Page 19: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.1.

>> repeat([2 3; 3 1; 4 2]

ans = [ 2 2 2 3 4 4 ]

function out = repeat1(m) out = [];[r, c] = size(m);for i = 1 : r %Go through each row for j = 1 : m(i, 2) %Repeat the number of times specified in the second column out(end + 1) = m(i, 1); endend

Can you rewrite this only one for loop?

Page 20: Chapter 8 Loops while loop syntax while ;... end;
Page 21: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.4. Write a function myfind, that mimics the behavior of the built-in function find. That is, it takes as input a boolean vector of 1’s and 0’s.

Page 22: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.4. Write a function myfind, that mimics the behavior of the built-in function find. That is, it takes as input a boolean vector of 1’s and 0’s. Not correct!

function out = myfind(A, x) out = []; for j = 1:length(A) if A(j) == x out = [out, j]; end;

Correct Code:

function res = myfind(v) res = [ ]; for j = 1: length(v) if v(j) out = [out, j ] end end

Page 23: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.8

Write a function intoBits to take an integer number as input and output a string of 0’s and 1’s representing the number in base 2.

Page 24: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.11

Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

Page 25: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.11

Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

function res = minAll(m)[r, c] = size(m); res = m(1, 1); %Set up the first temporary minimum for i = 1 : r %Going through each row for j = 1 : c %Going throuch each column if res > m(i, j) %Updating if necessary res = m(i, j) end endend

Page 26: Chapter 8 Loops while loop syntax while ;... end;

Exercise 8.11

Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

function res = minRow(m)[r, c] = size(m);res = zeros(1, r); %Set up resfor i = 1 : r %Going through each rowres(i) = m(i, 1); %Set up the first temporary minimum for row ifor j = 2 : c %Going throuch each columnif res(i) > m(i, j) %Updating if necessaryres(i) = m(i, j);endendend