I need my code to work/dont know what is going wrong.
Show older comments
I am working on a MATLAB assignment where I need to create a custom function called r_wheel.
The function should:
- Take two inputs: bet_color and bet_amount
- Return three outputs:
- result_message (string saying if the bettor won or lost)
- winner (0 if lost, 1 if won)
- wager_message (string saying how much money was won or lost)
The payout rules are:
- Red/Black → 1:1 payout
- Green → 17:1 payout
- If the bettor loses, they lose the amount wagered.
After that, I need to write a script that runs the function 100 times betting on "red" and calculates the odds of winning.
My issue is that I am not understanding how to get the function to be repeated multiple times and also add to a separate counter.
The error message I get is (Index exceeds the number of array elements. Index must not exceed 1.) Also, the code does not add to a counter, it instead only displays the answer one time.
This is the code for the function I made
function [result_msg,winner,wager_message] = r_wheel(bet_color, bet_amount)
disp('Spinning...')
pause(2) %delay for suspense
random_int=randi([1 38]); %random # between 1 and 38
if random_int < 3 % if the # is less 1 or 2 then result is green
result_color = 'Green'
wager_message = bet_amount*17 + bet_amount;
elseif (random_int <21) && (random_int>2)
result_color = 'Red' % if # is between 3 and 20 result is red
wager_message = bet_amount*2;
else
result_color = 'Black' %if # is between 21 and 38 the result is black
wager_message = bet_amount*2;
end
disp(result_color)
if strcmp(result_color, bet_color) % using string compare function to chekc if strings are the same
result_msg = 'Congratulations! You win!'; % if bet color is correct set result to win
winner = 1; %set winner variable to 1
wager_message = wager_message
else
result_msg = 'Sorry, you lose. Better luck next time!'; %if the bet color is not the same as result color set message
winner = 0; %set winner variable to 0
wager_message = -bet_amount
end
end
And here is the code for the loop.
clc, clear
x='Red'
y= 15
win_count = 0
for i = 1:100
[result,winner]=r_wheel(x, y) % runs the function
win_count = 0
[result,winner]=r_wheel(x, y)
if winner(i)==1
win_count(i) = win_count(i)+1
else
win_count(i)= win_count(i)
end
end
disp(win_count)
disp(result)
Accepted Answer
More Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!