How do I sum the outputs of a for loop?

10 次查看(过去 30 天)
I`ve created this code to simulate winning the lottery if the person plays 100 times with same numbers. I want to add up the total winnings from the 100 times but not sure how to write the code.
%Player`s Numbers
PLayers_Numbers = input('Pick 6 different numbers from 1 to 59(Vector form):')
for i = 1:1:100
%Winning Numbers
Winning_Numbers = datasample(1:59,6);
%Number of correct numbers
Matching_Numbers = ismember(Winning_Numbers,PLayers_Numbers);
Correct_Numbers = nnz(Matching_Numbers);
%Calculation of Winnings
switch Correct_Numbers
case{3}
Winnings = 25
case{4}
Winnings = 100
case{5}
Winnings = 1000
case{6}
Winnings = 1000000
otherwise
Winnings = 0;
end
end

采纳的回答

Rik
Rik 2020-2-18
Create a variable before the loop and set it to 0. Inside the loop you can add the value of Winnings to this variable.
  8 个评论
Rik
Rik 2020-2-18
That will take 40 times as much time to calculate. Have you waited that long?
Another strategy is to to simulate the choices all at once. Your current code simply repeats the same thing 100 times, but what you probably want is to generate a random vector with randi(59,1,6). If you do randi(59,4000,6) instead, you can remove most of the iterations. I'm on mobile, so writing example code is a bit difficult.
Matlab code is never too complex for your computer to run. It may be too complex for you to write it without a mistake, or it may be too slow. A faster computer will be faster, but better written code will be much more effective in saving time.
Georgia Parry
Georgia Parry 2020-2-18
okay thank you for all the help. Been very very helpful

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by