I need helping writing this code in Matlab. 1. In lottery the player has to gues
ID: 3041602 • Letter: I
Question
I need helping writing this code in Matlab.
1. In lottery the player has to guess correctly r numbers that are drawn out of n numbers. The probability, P, of guessing m numbers out of the r numbers can be calculated by the expression: rn-r - u . In this problem, we want to write a user-defined MATLAB r) r!(n-r) function that calculates P. (a) The factorial n! of a positive integer is defined by n!=n(n-1) (n-2) 2.1 , where 01=1. Write a user-defined function y = myfactfn(n) that calculates the factorial n!. The function should display an error message if a negative number is entered. Do not use MATLAB built-in function factorial (b) Write a user-defined function y=myBinon(n, r) that calculates n! Use myfactfn as a subfunction inside myBinom (n,r) for r) ri(n-r)! calculating factorial n!. (c) Write a user-defined function P LotteryProb (m,r,n). The input arguments are m the number of correct guesses; r, the number of numbers that need to be guessed; n, the number of numbers available. Use myBinom as a subfunction inside LotteryProb for calculating binomial coefficient (d) Use LotteryProb to calculate the probability of correctly selecting 2 of 5 the numbers that are drawn out of 30 numbers in a lottery game.Explanation / Answer
(a) the myfactfn function file will look like this (contents of myfactfn.m):
===============================
function y = myfactfn(n)
if n < 0
error("argument cannot be negative")
end
y = 1;
for i = 2:n
y = y * i;
end
end
===============================
(b) The myBinom function file will look like this (contents of myBinom.m):
===============================
function y = myBinom(n, r)
if n < r
error("first argument cannot be less than second argument")
end
y = myfactfn(n) / myfactfn(r) / myfactfn(n-r);
end
===============================
(c) The LotteryProb function file will look like this (contents of LotteryProb.m):
===============================
function P = LotteryProb(m, r, n)
if n < r
error("third argument cannot be less than second argument")
end
if r < m
error("second argument cannot be less than first argument")
end
P = myBinom(r, m) * myBinom(n - r, r - m) / myBinom(n, r);
end
===============================
(d) The function call will be LotteryProb(2, 5, 30). The output is:
>> LotteryProb(2,5,30)
ans = 0.16140