如何根据概率选择一个元素?

时间:2014-10-20 16:32:39

标签: matlab probability stochastic-process

让我们说我有一个包含N个元素的向量,每个元素都是它的概率。例如,v = [0.01 0.01 0.09 0.82 0.07]

所以我想要一个函数f(v),它在82%的时间返回4,在9%的时间返回3等。

输入向量v始终被归一化为sum(v) = 1,这可以是一种简化。

如何在MATLAB中实现这个概率函数?或者也许有一个内置功能呢?

2 个答案:

答案 0 :(得分:4)

如果您有统计工具箱,则可以使用randsample

f = randsample(1:numel(v), 1, true, v) 

这样做是从矢量1:numel(v)中取一个随机数,概率分布在v中给出。如果需要多个值,可以将第二个参数更改为所需的随机数。

答案 1 :(得分:4)

如果您 NOT 拥有统计工具箱(否则请参阅Stewie's answer)派生经验cdf,然后使用inverse sampling

% Numbers of draws
N = 1e3; 
% Sample a uniform in (0, 1)
x = rand(N,1);

% Empirical cdf
ecdf = cumsum([0, v]);

% Inverse sampling/binning 
[counts, bin] = histc(x,ecdf);

bin直接映射到v。因此,如果您有一组具有概率y的通用值v,则应采取:

out = y(bin);

注意,随着绘制数量N的增加,我们可以更好地逼近概率:

counts(end) = []; % Discard last bucket x==1
counts./sum(counts)

该功能可以是:

function [x, counts] = mysample(prob, val, N)
if nargin < 2 || isempty(val), val = 1:numel(prob); end
if nargin < 3 || isempty(N),   N   = 1;             end 

[counts, bin] = histc(rand(N,1), cumsum([0, prob(:)']));
x = val(bin);

end 
相关问题