Storing output values from a nested while loop
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
vijaya lakshmi
2018-3-21
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];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!