ET601!1!2 - Basic MATLAB Programming_2

Embed Size (px)

Citation preview

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    1/40

    The word dice

    52

    Historically, dice is the plural of die.

    In modern standard English, dice is used as both thesingular and the plural.

    Example of 19th Century bone dice

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    2/40

    Advanced dice

    53

    [ http://gmdice.com/ ]

    http://gmdice.com/http://gmdice.com/
  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    3/40

    randi function

    54

    Generate uniformly distributed pseudorandom integers randi(imax) returns a scalar value between 1 andimax.

    randi(imax,m,n) and randi(imax,[m,n])

    return an m-by-n matrix containing pseudorandom integervalues drawn from the discrete uniform distribution on theinterval [1,imax].

    randi(imax) is the same as randi(imax,1).

    randi([imin,imax],...) returns an arraycontaining integer values drawn from the discrete uniformdistribution on the interval [imin,imax].

    We have already seen the rand and randn functions.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    4/40

    randi function: Example

    55

    close all; clear all;N = 1e3; % Number of trials (number of times that the coin is tossed)s = (rand(1,N) < 0.5); % Generate a sequence of N Coin Tosses.

    % The results are saved in a row vector s.NH = cumsum(s); % Count the number of heads

    plot(NH./(1:N)) % Plot the relative frequencies

    LLN_cointoss.m

    Same as

    randi([0,1],1,N);

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    5/40

    Dice Simulator

    56

    http://www.dicesimulator.com/

    Support up to 6 dice and also has some background

    information on dice and random numbers.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    6/40

    Two Dice

    57

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    7/40

    Two-Dice Statistics

    58

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    8/40

    Classical Probability

    59

    Assumptions The number of possible outcomes is finite.Equipossibility: The outcomes have equal probability of

    occurrence. Equi-possible; equi-probable; euqally likely; fair

    The bases for identifying equipossibility were often physical symmetry (e.g. a well-balanced die, made of homogeneous

    material in a cubical shape)

    a balance of information or knowledge concerning the various possibleoutcomes.

    Formula: A probability is a fraction in which the bottomrepresents the number of possible outcomes, while the number ontop represents the number of outcomes in which the event ofinterest occurs.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    9/40

    Two Dice

    60

    A pair of dice

    Double six

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    10/40

    Two dice: Simulation

    61

    [ http://www2.whidbey.net/ohmsmath/webwork/javascript/dice2rol.htm ]

    http://www2.whidbey.net/ohmsmath/webwork/javascript/dice2rol.htmhttp://www2.whidbey.net/ohmsmath/webwork/javascript/dice2rol.htm
  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    11/40

    Two dice

    62

    Assume that the two dice are fair and independent.

    P[sum of the two dice = 5] = 4/36

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    12/40

    Two dice

    63

    Assume that the two dice are fair and independent.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    13/40

    Two-Dice Statistics

    64

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    14/40

    Leibnizs Error (1768)

    65

    Though one of the finest minds of his age, Leibniz was notimmune to blunders: he thought it just as easy to throw 12with a pair of dice as to throw 11.

    The truth is...

    Leibniz is a German philosopher, mathematician,and statesman who developed differential andintegral calculus independently of Isaac Newton.

    2[sum of the two dice = 11]36

    1[sum of the two dice = 12]

    36

    P

    P

    [Gorroochurn, 2012]

    0 100 200 300 400 500 600 700 800 900 10000

    0.05

    0.1

    0.15

    0.2

    0.25

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    15/40

    Two dice: MATLAB Simulation

    66

    n = 1e3;Number_Dice = 2;D = randi([1,6],Number_Dice,n);S = sum(D); % sum along each column

    RF11 = cumsum(S==11)./(1:n);plot(1:n,RF11)hold on

    RF12 = cumsum(S==12)./(1:n);plot(1:n,RF12,'r')

    0 100 200 300 400 500 600 700 800 900 10000

    0.01

    0.02

    0.03

    0.04

    0.05

    0.06

    0.07

    0.08

    [SumofTwoDice.m]

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    16/40

    Concatenation

    67

    Concatenation is the process ofjoining arrays to make larger ones.

    The pair of square brackets [] isthe concatenation operator.

    Horizontal concatenation:

    Concatenate arrays horizontallyusing commas.

    Each array must have the samenumber of rows.

    Vertical concatenation:

    Concatenate arrays vertically usingsemicolons.

    The arrays must have the samenumber of columns.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    17/40

    More on plot: Line specification

    68

    Various line types (styles), plot symbols (markers) and colorsmay be obtained with plot(X,Y,S) where S is a character

    string made from one element from any or all the following 3

    columns:

    y yellow . point - solid

    m magenta o circle : dotted

    c cyan x x-mark -. dashdot

    r red + plus -- dashed

    g green * star

    b blue s square

    w white d diamond

    k black v triangle (down)

    ^ triangle (up)

    < triangle (left)

    > triangle (right)

    p pentagram

    h hexagram

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    18/40

    Character Strings

    69

    A character string is asequence of any number ofcharacters enclosed in singlequotes.

    If the text includes a singlequote, use two single quoteswithin the definition.

    These sequences are arrays,like all MATLAB variables.

    Their class or data type ischar, which is short for

    character. You can concatenate strings

    with square brackets, just asyou concatenate numericarrays.

    To convert numeric valuesto strings, use functions,

    such as num2str or

    int2str.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    19/40

    More on plot : Examples

    70

    PLOT(X,Y,'c+:')plo

    ts a cyan dotted line with a

    plus at each data point

    0 1 2 3 4 5 6 7 8 9 10-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1

    0 1 2 3 4 5 6 7 8 9 10-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1

    PLOT(X,Y,'bd')plots

    blue diamond at each data point

    but does not draw any line

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    20/40

    More on plot : Axes and Title

    71

    0 1 2 3 4 5 6 7 8 9 10-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1sin and cos functions

    x

    y

    y = sin(x)

    y = cos(x)

    x = linspace(0,10,100);

    y1 = sin(x);

    y2 = cos(x);plot(x,y1,'mo--',x,y2,'bs--')

    title('sin and cos functions')

    xlabel('x')

    ylabel('y')

    legend('y = sin(x)','y = cos(x)')

    grid on

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    21/40

    Two dice: MATLAB Simulation

    72

    [SumofTwoDice.m]

    0 100 200 300 400 500 600 700 800 900 10000

    0.05

    0.1

    0.15

    0.2

    0.25

    0.3

    0.35

    0.4

    0.45

    0.5

    Number of Rolls

    Relative

    Frequency

    Sum = 11Sum = 12

    n = 1e3;Number_Dice = 2;D = randi([1,6],Number_Dice,n);S = sum(D); % sum along each column

    RF11 = cumsum(S==11)./(1:n);plot(1:n,RF11)

    hold onRF12 = cumsum(S==12)./(1:n);plot(1:n,RF12,'r')

    xlabel('Number of Rolls')ylabel('Relative Frequency')legend('Sum = 11', 'Sum = 12')grid on

    figureS_Support = (1*Number_Dice):(6*Number_Dice);hist(S,S_Support)

    N_S_Sim = hist(S,S_Support);

    2 3 4 5 6 7 8 9 10 11 120

    20

    40

    60

    80

    100

    120

    140

    160

    180

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    22/40

    Loops

    73

    Loops are MATLAB constructs that permit us to execute asequence of statements more than once.

    There are two basic forms of loop constructs:

    while loops and

    for loops. The major difference between these two types of loops is in

    how the repetition is controlled.

    The code in a while loop is repeated an indefinite number of

    times until some user-specified condition is satisfied. By contrast, the code in a for loop is repeated a specified

    number of times, and the number of repetitions is knownbefore the loops starts.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    23/40

    for loop: a preview

    74

    Execute a block of statements a specified number of times.

    k is the loop variable (also known as the loop index oriterator variable).

    expr is the loop control expression, whose resultusually takes the form of a vector.

    The elements in the vector are stored one at a time in the

    variable k, and then the loop body is executed, so that the loopis executed once for each element in the array produced byexpr.

    The statements between the for statement and the endstatement are known as the body of the loop. They areexecuted repeatedly during each pass of the for loop.

    for = exprk bodyend

    fork = 1:5x = k

    end

    for_ex1.m

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    24/40

    Two dice: Probability Calculation

    75

    Generate all the 36 possibilities.

    Find the corresponding sum.

    Count how many, among the

    36, have a particular value.

    Nested loops

    Number_Dice = 2;Dice_Support = 1:6;S_Support = (1*Number_Dice):(6*Number_Dice);S = [];fork1 = Dice_Support

    fork2 = Dice_SupportS = [S k1+k2];

    endendSize_SampleSpace = length(S);

    Number_11 = sum(S==11)Number_12 = sum(S==12)

    % Count all possible cases at once

    N_S = hist(S,S_Support)

    P = sym(N_S)/Size_SampleSpace

    Concatenation

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    25/40

    Vectorization and Preallocation

    76

    LLN_cointoss.m

    LLN_cointoss_for_preallocated.m

    close all; clear all;

    N = 1e3; % Number of trials

    s = zeros(1,N); % Preallocation

    s(1) = randi([0,1]);

    fork = 2:N

    s(k) = randi([0,1]);

    end

    NH = cumsum(s); % Count the number of heads

    plot(NH./(1:N)) % Plot relative frequencies

    The script will still run without this line.

    Revisiting an old script:

    close all; clear all;N = 1e3; % Number of trials (number of times that the coin is tossed)s = randi([0,1],1,N); % Generate a sequence of N Coin Tosses.

    % The results are saved in a row vector s.NH = cumsum(s); % Count the number of heads

    plot(NH./(1:N)) % Plot the relative frequencies

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    26/40

    Preallocating Vectors (or Arrays)

    77

    Used when the content of a vector is computed/added/known while the loop isexecuted.

    One method is to start with an empty vector and extend the vector by addingeach number to it as the numbers are computed. Inefficient.

    Every time a vector is extended a new chunk of memory must be found

    that is large enough for the new vector, and all of the values must be copied fromthe original location in memory to the new one. This can take a long time.

    A better method is to preallocate the vector to the correct size and thenchange the value of each element to store the desired value. This method involves referring to each index in the output vector, and placing

    each number into the next element in the output vector.

    This method is far superior, if it is known ahead of time how many elements thevector will have.

    One common method is to use the zeros function to preallocate the vector tothe correct length.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    27/40

    zeros, ones, eye

    78

    zeros Create array of all zeros.

    zeros returns the scalar 0. zeros(n) returns an n-by-n matrix of zeros. zeros(n,m) returns an n-by-m matrix of

    zeros.

    ones Create array of all ones.

    eye Create identity matrix.

    eye returns the scalar, 1.

    eye(n) returns an n-by-n identity matrix withones on the main diagonal and zeros elsewhere.

    eye(n,m) returns an n-by-m matrix with oneson the main diagonal and zeros elsewhere.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    28/40

    Exercise

    79

    The following scriptwas used to calculatethe probabilities relatedto the sum resultingfrom a roll of two dice.

    Modify the script hereso that the vector S ispreallocated.

    Modify the script toalso create a matrix SS.

    Its size is 6

    6. Thevalue of its (k1,k2)element should bek1+k2.

    Number_Dice = 2;Dice_Support = 1:6;S_Support = (1*Number_Dice):(6*Number_Dice);S = [];fork1 = Dice_Support

    fork2 = Dice_SupportS = [S k1+k2];

    endendSize_SampleSpace = length(S);

    Number_11 = sum(S==11)Number_12 = sum(S==12)

    % Count all possible cases at once

    N_S = hist(S,S_Support)

    P = sym(N_S)/Size_SampleSpace

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    29/40

    Galileo and the Duke of Tuscany

    (1620)

    80

    When you toss three dice, the chance of the sum being 10 isgreater than the chance of the sum being 9.

    The Grand Duke of Tuscany ordered Galileo to explain a paradox

    arising in the experiment of tossing three dice:

    Why, although there were an equal number of 6 partitions of thenumbers 9 and 10, did experience state that the chance of throwing a

    total 9 with three fair dice was less than that of throwing a total of

    10?

    Partitions of sums 11, 12, 9 and 10 of the game of three fair dice:

    [Gorroochurn, 2012]

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    30/40

    Exercise

    81

    Write a MATLAB script to Simulate N = 1000 repeated rolls of three dices.

    Calculate the sum of the three dices from the rollsabove.

    Plot the relative frequency for the event that thesum is 9.

    In the same figure, plot (in red) the relativefrequency for the event that the sum is 10.

    In another figure, create a histogram for the sumafter N rolls of three dice.

    Calculate the actual probability for each possible

    value of the sum. In another figure, compare the probability with the

    relative frequency obtained after the N simulations.

    2 4 6 8 10 12 14 16 180

    0.02

    0.04

    0.06

    0.08

    0.1

    0.12

    0.14

    sum of three dice

    probability

    relative frequency

    0 100 200 300 400 500 600 700 800 900 10000

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    Number of Rolls

    RelativeFrequen

    cy

    Sum = 11

    Sum = 12

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    31/40

    Three-Dimensional Arrays

    82

    Arrays in MATLAB are not limited to two dimensions.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    32/40

    Three-Dimensional Arrays

    83

    Three-dimensional arrays can be created directly using functionssuch as the zeros,ones, rand, and randi functions byspecifying three dimensions to begin with.

    For example,zeros(4,3,2) will create a 432 matrix ofall 0s.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    33/40

    Empty Array

    84

    An array that stores no value Created using empty square

    brackets: []

    Values can then be added by

    concatenating. Can be used to delete elements

    from vectors or matrices.

    Individual elements cannot be

    removed from matrices. Matrices always have to have the same

    number of elements in every row.

    Entire rows or columns could be

    removed from a matrix.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    34/40

    Scandal of Arithmetic

    85

    Which is more likely, obtaining at least one

    six in 4 tosses of a fair dice (event A), or

    obtaining at least one double six in 24 tosses

    of a pair of dice (event B)?

    44 4

    4

    2424 24

    24

    6 5 5( ) 1 .518

    6 6

    36 35 35( ) 1 .491

    36 36

    P A

    P B

    [http://www.youtube.com/watch?v=MrVD4q1m1Vo]

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    35/40

    Origin of Probability Theory

    86

    Probability theory was originally inspired by gamblingproblems.

    In 1654, Chevalier de Mr invented a gambling systemwhich bet even money on case B.

    When he began losing money, he asked his mathematicianfriend BlaisePascal to analyze his gambling system.

    Pascal discovered that the Chevalier's system would loseabout 51 percent of the time.

    Pascal became so interested in probability and together withanother famous mathematician, Pierre de Fermat, they laidthe foundation of probability theory.

    best known for Fermat's Last Theorem

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    36/40

    Branching Statements if statement

    87

    General form:

    The statements are executed if the real part of the expression has

    all non-zero elements.

    Zero or more ELSEIF parts can be used as well as nested ifs.

    The expression usually contains ==, , =, or ~=.

    if expressionstatements

    elseif expression

    statements

    else

    statementsend

    The ELSE and ELSEIF parts

    are optional.

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    37/40

    Example: Assigning Grades

    88

    Pass vs. Fail

    % Generate a random number

    score = randi(100, 1)

    ifscore >= 50

    grade = 'pass'else

    grade = 'fail'

    end

    score 50true false

    grade = pass grade = fail

    if_ex_1.m

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    38/40

    Example: Assigning Letter Grades

    89

    score 80

    score 70

    score 60

    score 50

    true false

    true false

    true false

    true false

    grade = A

    grade = B

    grade = C

    grade = D grade = F

    % Generate a random numberscore = randi(100, 1)

    ifscore >= 80

    grade = 'A'

    elseifscore >= 70

    grade = 'B'

    elseifscore >= 60

    grade = 'C'

    elseifscore >= 50

    grade = 'D'

    else

    grade = 'F'

    end

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    39/40

    Exercise

    90

    Write a MATLAB script to evaluate the relative frequenciesinvolved in the scandal of arithmetic.

    0 100 200 300 400 500 600 700 800 900 10000

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    number of rolls

    relativefrequency

    Event A: At least one six in 4 tosses of a fair dice

    Event B: At least one double six in 24 tosses of a pair of dice

  • 7/23/2019 ET601!1!2 - Basic MATLAB Programming_2

    40/40

    Exercise

    91

    Write a MATLAB script to evaluate the relative frequenciesinvolved in the Monty Hall game.

    0 100 200 300 400 500 600 700 800 900 10000

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    0.8

    0.9

    1

    Number of Trials

    RelativeFrequencyofWinning

    Not Switch

    Swicth