drnd.m

来自「sexy函数可以将MATLAB符号表达式变成人们书写形式的表达式。 drnd函」· M 代码 · 共 21 行

M
21 行
字号
function out=drnd(p,n)
%out=drnd(p,n)
%copyright:rocwoods
%p is the probability distribution matrix;
%n is the number of the samples you want to generate;
%=================
%for example
%a random variable x can be 1,2,3,4,5 with the probability 0.1 0.2 0.25 0.3 0.15(whose sum equals to 1)
%then to generate 1000 samples of x,we can make it as below:
%out=drnd([1 2 3 4 5;0.1 0.2 0.25 0.3 0.15],1000)
a=cumsum(p(2,:));
b=rand(n,1);
out=zeros(1,n);
for k=1:n
    c=find(a<b(k));
    if (isempty(c))
        out(k)=p(1,1);
    else
        out(k)=p(1,c(end)+1);
    end
end

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?