Clear Filters
Clear Filters

Storing output values from a nested while loop

1 view (last 30 days)
How can I get the values for "gens" to change after every loop and store it in the row vector that I created?
prob_vec=[0.2 0.5 0.3]; % prob of having a male offspring
max_son=length(prob_vec)-1; % max amount of sons
cum_prob=cumsum(prob_vec);
sim=3;
men=1;
extinct=0;
gens=0;
total_gens=(0); %running total
for n=1:sim
while (men > 0) && (men < 100)
% Array of random numbers to determine # of kids for each person.
num=rand(men,1);
% Increment the number of generations.
gens=gens+1;
% Number of men in the next generation.
men=0;
for j=1:max_son
%finds indices of men who have j male offspring
men = men + j * length(find((num>cum_prob(j)) & (num<=cum_prob(j+1))));
end % end of for loop for max sons
if(men==0)
extinct=1;
break;
end
end %end of while loop
total_gens(n+1)=total_gens(n)+gens; % the loop uses the same value of gen 3 times
end % end of the for loop
total_gens(1)=[]; deletes the first element which is 0 from the array
avg=mean(total_gens); %finds the average of the array

Answers (1)

vijaya lakshmi
vijaya lakshmi on 21 Mar 2018
Hi Harrison,
U can create a row vector initially as out=[];
Later store the value of gens in vector 'out' using concatenation
gens=gens+1;
out=[out gens];

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!