Filter löschen
Filter löschen

Storing output values from a nested while loop

1 Ansicht (letzte 30 Tage)
Harrison
Harrison am 15 Mär. 2018
Beantwortet: vijaya lakshmi am 21 Mär. 2018
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

Antworten (1)

vijaya lakshmi
vijaya lakshmi am 21 Mär. 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];

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by