Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

matlab code Write a MATLAB script to simulate tossing coins. First ask the user

ID: 1766116 • Letter: M

Question

matlab code

Write a MATLAB script to simulate tossing coins. First ask the user how many times (call it n) he/she wants to toss the coins. Use randi function to generate random integers of 1 or 2. Assume 1 represents Heads and 2 represents Tails. 1. Toss a coin n times and calculate how many times it lands Heads up. 2. Toss two coins simultaneously n times and calculate how many times they land the same (both Heads up or both Tails up). 3. Toss three coins simultaneously n times and calculate how many times at least one of them lands Heads up Run your code for n = 10, 100, 1000 and report the results using fprintf Hint: To answer part 3, it is easier to calculate the complimentary event (How many times none of the three coins land Heads up, or in other words, how many times all three coins land Tails up)

Explanation / Answer

MATLAB code is given below.

clc;
close all;
clear all;

n = input('Enter number of times to toss coin/coins: ');
fid=fopen('toss_coin.dat','w');

% Question 1
% Toss a coin n times and get a heads up.
Times_Heads_up = length(find( ceil(rand(1,n)*2) == 1))


% Question 2
% Toss 2 coins n times and get the heads the same on both coins.
A = ceil(rand(1,n)*2);
B = ceil(rand(1,n)*2);
Times_2coins_same = length(find(A == B))


% Question 3
% Toss 3 coins n time and find how many times at least one coin turns head up
C = ceil(rand(1,n)*2);% 1st coin n times
D = ceil(rand(1,n)*2);% 2nd coin n times
E = ceil(rand(1,n)*2);% 3rd coin n times
i = 0;
for k = 1:length(A)
if (C(k) == 2 && D(k) == 2 && E(k) == 2)
i = i+1;
end
end
Time_atleast_one_heads_up = n-i


fprintf(fid,'%6.3f %6.3f %6.3f',...
Times_Heads_up,Times_2coins_same,Time_atleast_one_heads_up);

Results:

Enter number of times to toss a coin/coins: 10

Times_Heads_up =

4


Times_2coins_same =

8


Time_atleast_one_heads_up =

9

Enter number of times to toss a coin/coins: 100

Times_Heads_up =

39


Times_2coins_same =

51


Time_atleast_one_heads_up =

88

Enter number of times to toss a coin/coins: 1000

Times_Heads_up =

509


Times_2coins_same =

503


Time_atleast_one_heads_up =

871