[MATLAB] For loop looping too many times?

Posted 16 April 2019 - 02:31 PM

I believe something is wrong with my for loop, but I can't quite understand what it is.
Here is the code:
num_people = 200;
num_simulations = 10000;
probability = rand(num_simulations, num_people);
initial_five_dollar_bills = 1:50;

for i5db = initial_five_dollar_bills

no_change_needed = 0;

for k = 1:num_simulations
count = i5db;
need_change = 0;

for p = 1:num_people

if probability(k,p) > 0.5
count = count + 1;
elseif probability(k,p) < 0.5
count = count - 1;
end

if count < 0
need_change = need_change + 1;
end
end

if need_change == 0
no_change_needed = no_change_needed + 1;
end

need_change_total = need_change;
percent_success = no_change_needed / k;

output_data_sim(k,:)/>/> = [i5db,need_change_total,percent_success;];
end

output_data_i5db(i5db,:)/>/> = [i5db,mean(output_data_sim(:,2)), mean(output_data_sim(:,1))];

end

score = find(output_data_i5db(:,3)>=0.95,1);
five_dollar_bills_needed = output_data_i5db(score,1);
probability_percent = output_data_i5db(score,3)*100;
Initial_5s = output_data_i5db(:,1);
Avg_5s_Needed = output_data_i5db(:,2);
Avg_Probability = output_data_i5db(:,3);
table_header = {'\$5 Bills Count','Average \$5 Bills Needed', 'Average Probability'};

Output_Table = table(Initial_5s,Avg_5s_Needed,Avg_Probability)

fprintf('\nStarting \$5 bill count range: %d to %d\n', min(initial_five_dollar_bills), max(initial_five_dollar_bills));
fprintf('\nNumber of simulations for each starting \$5 bill count: %d', num_simulations);
fprintf('\n%.2f%% probability of having enough change in \$5 bills. \n',Avg_Probability);
fprintf('\n\n');

Attached are the output I am currently getting, and what the desired output should look like

The first two pictures are the output I am looking to get, and the second two pictures are the output I am currently getting

The first two pictures are the output I am expecting to get, the second two pictures are the output I am currently getting

Attached image(s)

• • • • This post has been edited by andrewsw: 17 April 2019 - 03:30 AM
Reason for edit:: added MATLAB to title

Is This A Good Question/Topic? 0

Replies To: [MATLAB] For loop looping too many times?

#2 modi123_1 • • Suitor #2
•    Reputation: 15262
• Posts: 61,174
• Joined: 12-June 08

Re: [MATLAB] For loop looping too many times?

Posted 16 April 2019 - 02:31 PM

What language is this?

Re: [MATLAB] For loop looping too many times?

Posted 16 April 2019 - 02:32 PM

MATLAB, sorry I forgot to mention in my OP

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }