从计数向量中随机选取元素

时间:2015-12-19 23:14:11

标签: algorithm matlab statistics octave

我目前正在尝试通过算法更改优化一些MATLAB / Octave代码,但无法在此处弄清楚如何处理一些随机性。假设我有一个整数向量V,每个元素代表一些事物的数量,在我的情况下是光子。现在我想随机挑选一些"东西"并创建一个相同大小的新矢量,但调整了计数。

这是我现在如何做到这一点:

function W = photonfilter(V, eff)
% W = photonfilter(V, eff)
% Randomly takes photons from V according to the given efficiency.
%
% Args:
%  V: Input vector containing the number of emitted photons in each
%     timeslot (one element is one timeslot). The elements are rounded
%     to integers before processing.
%  eff: Filter efficiency. On the average, every 1/eff photon will be
%       taken. This value must be in the range 0 < eff <= 1.
%  W: Output row vector with the same length as V and containing the number
%     of received photons in each timeslot.
%
% WARNING: This function operates on a photon-by-photon basis in that it
% constructs a vector with one element per photon. The storage requirements
% therefore directly depend on sum(V), not only on the length of V.

% Round V and make it flat.
Ntot = length(V);
V = round(V);
V = V(:);

% Initialize the photon-based vector, so that each element contains
% the original index of the photon.
idxV = zeros(1, sum(V), 'uint32');
iout = 1;
for i = 1:Ntot
  N = V(i);
  idxV(iout:iout+N-1) = i;
  iout = iout + N;
end;

% Take random photons.
idxV = idxV(randperm(length(idxV)));
idxV = idxV(1:round(length(idxV)*eff));

% Generate the output vector by placing the remaining photons back
% into their timeslots.
[W, trash] = hist(idxV, 1:Ntot);

这是上述描述的相当简单的实现。但它有一个明显的性能缺点:该函数创建一个向量(idxV),每个光子包含一个元素。因此,如果我的V只有1000个元素,但每个元素的平均数为10000,那么内部向量将有1000万个元素,使得函数变得缓慢而沉重。

我现在想要实现的不是直接优化此代码,而是使用其他类型的算法立即计算新计数而不给每个光子某种&#34;身份&#34; 。这必须以某种方式实现,但我无法弄清楚如何去做。

要求:

  • 输出向量W必须与输入向量V具有相同数量的元素。
  • W(i)必须是整数并且以0 <= W(i)&lt; = V(i)为界。
  • sum(W)的期望值必须为sum(V)* eff。
  • 算法必须以某种方式实现这个&#34;随机选择&#34;光子,即不应该存在某些确定性部分,例如&#34;通过V将所有计数除以步长并传播余数&#34;,因为该函数的整个点是将随机性带入系统。
  • 如果不可避免,允许在V上显式循环,但最好采用矢量化方法。

任何想法如何实现这样的事情?仅使用随机向量然后使用概率和舍入的一些技巧的解决方案将是理想的,但到目前为止我还没有取得任何成功。

谢谢!最诚挚的问候,Philipp

0 个答案:

没有答案