% LMex020202_4th.m
% Example 2.2.2 Throwing 2 dice p
% Larsen & Marx (2006) Example 2.2.2, page 24 Figure 2.2.1
% Writtten by Eugene Gallagher, Eugene.Gallagher@umb.edu
% http://alpha.es.umb.edu/faculty/edg/files/edgwebp.html
% Written 9/17/2010 & last revised 1/13/2011
% What is the probability of rolling a 7 with two dice
% The dice are colored red and green, but that is irrelevant here.
green=1:6
red=green'
% tile rows down 6 times
green=repmat(green,6,1) % repmat is a built-in function
% for earlier versions of matlab, I used rowcopy and colcopy.m
% tile columns across 6 times
red=repmat(red,1,6) % Note that the 1 column green is replaced
% by a 6x6 matrix.
sumdice=red+green
[r,c]=size(sumdice) % returns the number of rows and columns
fprintf('Sample Space, with each sample outcome an ordered pair:\n')
fprintf('(%1.0f, %1.0f) (%1.0f, %1.0f) (%1.0f, %1.0f) (%1.0f, %1.0f) (%1.0f, %1.0f) (%1.0f, %1.0f)\n',[green(:)';red(:)'])
i=find(sumdice==7); % indices for event A: sum of faces=7
length(i)
fprintf(...
'%1.0f of the %2.0f sample outcomes in sample space S constitute the event A, rolling a 7:\n',...
length(i),r*c)
fprintf('(%1.0f,%1.0f)\n',[red(i) green(i)]')
% Not specified the problem, but here's the probability of rolling a 7:
P=length(i)/(r*c) % Probability of rolling a 7
% It is more accurate to express simple probabilities
% as fractions: 0.1667 is not exactly equal to 1/6
% Matlab can express results in fractional form
% by typing format rat, short for rational number format
format rat
disp('The probability of rolling a 7 with two dice is:')
P
% Here is one of many 1-line solutions to the problem
red=repmat(1:6,6,1);c=red+red';P=sum(c(:)==7)/length(c(:));
% typing format returns Matlab to its numerical default
format
% Translation of the 1-line program
% 1st repmat copies the row vector 1:6 down producing 6 rows of 1:6
% The sample space, c is created by adding the results of the red die to
% its transpose red'
% c represents the sample space, produced by summing 1:6 for first die &
% 1:6 for 2nd die
% c(:) converts any matrix to a single column of numbers
% c(:)==7, a logical statement, converts c to a set of 1's and 0's
% a 1 is entered if c equals 7, a zero if c(i) not equal to zero
% sum(c(:)==7) provides the number of elements equal to 9
% length(c(:)==7) provides the number of events in the sample space, 36.