给这段代码加注释 N= length(weight); N_babies= zeros(1,N); q_res = N.*weight; N_babies = fix(q_res); N_res=N-sum(N_babies); if (N_res~=0) q_res=(q_res-N_babies)/N_res; cumDist= cumsum(q_res); u = fliplr(cumprod(rand(1,N_res).^(1./(N_res:-1:1)))); j=1; for i=1:N_res while (u(1,i)>cumDist(1,j)) j=j+1; end N_babies(1,j)=N_babies(1,j)+1; end end index=1; for i=1:N if (N_babies(1,i)>0) for j=index:index+N_babies(1,i)-1 outIndex(j) = i; end end index= index+N_babies(1,i); end
时间: 2024-03-30 07:34:18 浏览: 138
# 统计权重数组的长度
N = length(weight)
# 初始化新生儿数量数组为全零
N_babies = zeros(1, N)
# 计算每个元素被选中的期望次数
q_res = N .* weight
# 取整得到每个元素实际被选中的次数
N_babies = fix(q_res)
# 计算剩余可分配数量
N_res = N - sum(N_babies)
# 如果有剩余数量需要分配
if (N_res ~= 0):
# 计算剩余数量的期望次数
q_res = (q_res - N_babies) / N_res
# 计算剩余数量的累积分布
cumDist = cumsum(q_res)
# 计算随机数数组
u = fliplr(cumprod(rand(1, N_res).^(1./(N_res:-1:1))))
# 初始化计数器
j = 1
# 分配剩余数量
for i in range(1, N_res+1):
while (u(1, i) > cumDist(1, j)):
j = j + 1
N_babies(1, j) = N_babies(1, j) + 1
# 初始化输出索引数组的起始位置
index = 1
# 根据每个元素被选中的次数,将其对应的索引添加到输出索引数组中
for i in range(1, N+1):
if (N_babies(1, i) > 0):
for j in range(index, index+N_babies(1, i)):
outIndex(j) = i
index = index + N_babies(1, i)
阅读全文