1 / 29

Chapter 8 Loops while loop syntax

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

sheera
Download Presentation

Chapter 8 Loops while loop syntax

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Example 1: We wrote a function insert that inserts A(k) in the array A(1:k – 1). Now we will write the function insertionsort to call insert iteratively. function 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;

  3. 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

  4. for loop syntax for j = 1:20 <statement sequence> end

  5. 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 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)

  6. 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;

  7. We will write three functions: toss() produces 1 or 2 with probability 0.5 tossgame()  produces 1 (2) 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

  8. 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

  9. 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 = – Sjpj log pj Goal is to compute the entropy of a given text.

  10. 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 >>

  11. 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.

  12. 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)

  13. Rules for recursive functions • 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. Recursion may be more time or memory consuming so should be careful with their use.

  14. 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;

  15. 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)

  16. Recursive binary search program function 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;

  17. Exercise 8.1. >> repeat([2 3; 3 1; 4 2] ans = [ 2 2 2 3 4 4 ]

  18. Exercise 8.1. >> repeat([2 3; 3 1; 4 2] ans = [ 2 2 2 3 4 4 ]

  19. 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); end end

  20. 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.

  21. 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.

  22. 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. • function out = myfind(A, x) • out = []; • for j = 1:length(A) • if A(j) == x • out = [out, j]; • end;

  23. 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.

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

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

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

  27. 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 end end

  28. 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 res for i = 1 : r %Going through each row res(i) = m(i, 1); %Set up the first temporary minimum for row i for j = 2 : c %Going throuch each column if res(i) > m(i, j) %Updating if necessary res(i) = m(i, j); end end end

More Related