matlab - How to choose one element based on its probability? -



matlab - How to choose one element based on its probability? -

this question has reply here:

generate random number given probability matlab 4 answers

let's have vector containing n elements, each beingness probability. example, v = [0.01 0.01 0.09 0.82 0.07]

so want function f(v) returns 4 @ 82% of time, 3 @ 9% of time etc.

the input vector v normalized sum(v) = 1, can simplification.

how can implement probabilistic function in matlab? or maybe there built-in function this?

if not have statistics toolbox (otherwise see stewie's answer) derive empirical cdf , utilize inverse sampling:

% numbers of draws n = 1e3; % sample uniform in (0, 1) x = rand(n,1); % empirical cdf ecdf = cumsum([0, v]); % inverse sampling/binning [counts, bin] = histc(x,ecdf);

where bin maps straight v. so, if have generic set of values y probabilitites v, should take:

out = y(bin);

note, number of draws n increases, improve approximation of probabilities:

counts(end) = []; % discard lastly bucket x==1 counts./sum(counts)

the function can be:

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

matlab probability stochastic-process

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -