How do I sum the outputs of a for loop?

조회 수: 9 (최근 30일)
Georgia Parry
Georgia Parry 2020년 2월 18일
댓글: Georgia Parry 2020년 2월 18일
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