Matlab错误:位置1的索引超出数组边界

Matlab错误:位置1的索引超出数组边界,matlab,gamma-distribution,gamma,Matlab,Gamma Distribution,Gamma,我试图在MATLAB中创建伽马分布;但是,我一直收到错误: 位置1中的索引超过数组边界(不得超过100) 假设我读的是正确的,它指的是变量M,它只是=2500(我在这个项目中使用的伪随机变量的数量) 我希望有人能解释我的逻辑出了什么问题,可能还有解决办法 alpha = 0.5; w = gamma_rdn(M,alpha); x1 = (0.0001:0.001:1); % For plot figure(5) subplot(2,1,1);hist(w);title('Histogram

我试图在MATLAB中创建伽马分布;但是,我一直收到错误:

位置1中的索引超过数组边界(不得超过100)

假设我读的是正确的,它指的是变量M,它只是=2500(我在这个项目中使用的伪随机变量的数量)

我希望有人能解释我的逻辑出了什么问题,可能还有解决办法

alpha = 0.5;
w = gamma_rdn(M,alpha);
x1 = (0.0001:0.001:1); % For plot

figure(5)
subplot(2,1,1);hist(w);title('Histogram of Gamma RDN');
subplot(2,1,2);plot(x1,pdf('gam',x1,alpha,1));title('Theoretical Gamma Density with \alpha = 0.5');
axis([0 1 0 100]);

% The gamma_rdn function is implemented as follows:
function[w] = gamma_rdn(M,alpha)
    % Generate random numbers from the gamma distribution with parameter
    % alpha <= 1, beta = 1
    pe = exp(1);
    w = zeros(M,1);
    u = rand(100,1);
    b = (alpha + pe)/pe;
    i = 0;
    j = 0;
    while j < M
        i = i+1;
        y = b*u(i,1);
        if y <= 1
            z = y^(1/alpha);
            i = i+1;
            if u(i,1) <= exp(-z)
                j = j+1;
                w(j,1) = z;
            else
                i = i+1;
            end
        else
            z = -log((b-y)/alpha);
            i = i+1;
            if u(i,1) <= z^(alpha - 1)
                j = j+1;
                w(j,1) = z;
            else
                i = i+1;
            end
        end
    end
    if i > 95
        u = rand(100,1);
        i = 0;
    end
end
alpha=0.5;
w=伽马密度(M,α);
x1=(0.0001:0.001:1);%阴谋
图(5)
子批次(2,1,1);hist(w);标题(“伽马RDN直方图”);
子批次(2,1,2);图(x1,pdf('gam',x1,alpha,1));标题(“理论伽马密度,α=0.5”);
轴([01100]);
%gamma_rdn函数的实现如下:
函数[w]=伽马(M,alpha)
%使用参数从gamma分布生成随机数

%alpha您选择u=rand(100,1)有什么特别的原因吗

问题的出现是因为在while循环中,一旦变量i超过100(比如i=101),y=b*u(i,1)就失效了。也就是说,您试图访问u(101,1),而u的大小是(100,1)


如果没有特殊原因,请尝试足够大的尺寸,例如,u=rand(10000,1)

谢谢,这可以解决问题!