在Matlab中生成三角分布 [英] Generating a triangular distribution in Matlab

查看:717
本文介绍了在Matlab中生成三角分布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Matlab中生成三角概率分布,但未成功.我在 http://en.wikipedia.org/wiki/Triangular_distribution 中使用了公式./p>

I have attempted to generate a triangular probability distribution in Matlab, but was not successful. I used the formula at http://en.wikipedia.org/wiki/Triangular_distribution.

n = 10000000;

a = 0.2;
b = 0.7;
c = 0.5;

u = sqrt(rand(n, 1));

x = zeros(n, 1);
for i = 1:n
    U = u(i);
    if U < (c-a)/(b-a)
        X = a + sqrt(U*(b-a)*(c-a));
    else
        X = b - sqrt((1-U)*(b-a)*(b-c));        
    end
    x(i) = X;
end

hist(x, 100);

直方图如下所示:

对我来说,看起来不太像一个三角形.有什么问题?我在滥用rand(n)吗?

Doesn't look like much of a triangle to me. What's the problem? Am I abusing rand(n)?

推荐答案

您可以将两个均匀分布加起来,分布图会卷积,然后得到三角形分布.

you can add up two uniform distributions, the distribution graphs convolve, and you get a triangular distribution.

简单易懂的示例:滚动两个骰子,每个动作具有均匀的分布以产生1-6的数字,组合的动作具有三角形分布以产生2-12的数字

easy-to-understand example: rolling two dice, each action has uniform distribution to result in a number from 1-6, combined action has triangular distribution to result in a number 2-12

最小的工作示例:

a=randint(10000,1,10);
b=randint(10000,1,10);

c=a+b;

hist(c,max(c)-min(c)+1)

edit2:再次在脚本中查找.它正在工作,但是您犯了一个错误:

edit2: looked in your script again. It's working but you've made one mistake:

u = sqrt(rand(n, 1));

应该是

u = rand(n, 1);

edit3:优化的代码

edit3: optimized code

n = 10000000;

a = 0.2;
b = 0.7;
c = 0.5;

u = rand(n, 1);
x = zeros(n, 1);

idx = find(u < (c-a)/(b-a));
x(idx) = a + sqrt(u(idx)*(b-a)*(c-a));
idx =setdiff(1:n,idx);
x(idx) = b - sqrt((1-u(idx))*(b-a)*(b-c));
hist(x, 100);

这篇关于在Matlab中生成三角分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆