In: Computer Science
The Monty Hall problem solved on Matlab. Please show code. You are given a choice between three doors. Behind one door is a new car and behind the other two doors is a goat. You first pick one of the doors at random. Then, a door with a goat is opened for you. You are then given the option to switch your door to the other unopened door. Should you do this? What are your odds of winning if you switch vs not switching? Show using matlab with a large number of runs, where you keep your selection 50% of the time and switch 50% of the time.
disp 'Let''s play the Monty Hall game!';
disp 'There is a car behind one of the three doors 1, 2, 3';
conti = "y";
switch_wins = 0;
not_switch_wins = 0;
% Iterate loop till user enters "y" for conti
while(conti!="n")
is_switched = false;
% Pick a number from 1,2,3
guess = input('Pick a door between 1, 2 or 3: ');
% Print the door user has picked
fprintf(['\nYou picked door number %d \n'],guess);
% Generate a random number for winning door
winningNumber = randi([1,3]);
% If user's guess is equal to winning door
if (guess == winningNumber)
% Generate a random number from the other two losing door
revealDoor = randi([1,3]);
% This loop is to make sure reveal door is not equal to winning
door
while (revealDoor==winningNumber)
revealDoor = randi([1,3]);
end
% If user's guess is not equal to winning door
else
% Generate reveal door apart from user's guess and winning
door
revealDoor = setdiff(1:3, [guess,winningNumber]);
end
% Print revealing door and print that it is a goat.
fprintf(['\nBefore we reveal what you have won, let''s see what you
have lost behind door %d \n'],revealDoor);
fprintf('It''s a goat!\n\n');
% Generate remaining door and ask if they want to switch with this
door
remainDoor = setdiff(1:3, [guess,revealDoor]);
choice = input(['Now, do you want to switch the door to '
num2str(remainDoor) '? [y/n] '],'s' );
% If they enter yes, switch it
if(choice == "y")
temp = guess;
guess = remainDoor;
remainDoor = temp;
is_switched = true;
end
% Now, check if user's guess is equal to winning number
% If yes, print congratualations
# Else, print the door number with car and that they have a won a
goat
if(guess == winningNumber)
fprintf('\nCongratulations, you win the car!\n');
if(is_switched)
switch_wins +=1;
else
not_switch_wins+=1;
end
else
fprintf(['\nThe car is behind door #%d ,and You have won a
goat!\n'],winningNumber);
end
% Ask if they want to play again
conti = input(['want to play again ? (y/n) '],'s' );
end
fprintf('Switched Wins = %d\n',switch_wins);
fprintf('Not Switched Wins = %d\n',not_switch_wins);
SCREENSHOT
OUTPUT