Matlab Error: Index in Position 1 exceeds array bounds

Matlab Error: Index in Position 1 exceeds array bounds

我正在尝试在 MATLAB 中创建伽玛分布;但是,我一直收到错误消息:

Index in Position 1 exceeds array bounds (must not exceed 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

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

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

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