How do I sum the outputs of a for loop?

9 visualizaciones (últimos 30 días)
Georgia Parry
Georgia Parry el 18 de Feb. de 2020
Comentada: Georgia Parry el 18 de Feb. de 2020
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

Respuesta aceptada

Rik
Rik el 18 de Feb. de 2020
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 comentarios
Rik
Rik el 18 de Feb. de 2020
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 el 18 de Feb. de 2020
okay thank you for all the help. Been very very helpful

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by