在MATLAB中按顺序读取矩阵列

时间:2014-09-12 11:33:53

标签: matlab

我最初的问题是创建一个场景,其中有一条特定长度的线(x = 100),以及特定位置的一个障碍(pos = 50)。进行多轮采样,在其中进行特定量的随机数(p)。生成的数字可以落在屏障的左侧或右侧。程序输出屏障左侧生成的最大数字与右侧生成的最小数字之间的差值。这里看得更清楚:

在此示例中,系统创建了4个数字(a,b,c,d)。它将忽略a和d并输出b和c之间的差异。基本上,它将输出仍包含屏障的线的最小可能片段。

我一直用来做的代码是:

x = 100;       % length of the grid
pos = 50;      % position of the barrier
len1 = 0;      % left edge of the grid
len2 = x;      % right edge of the grid

sample = 1000; % number of samples to make
nn     = 1:12  % number of points to generate (will loop over these)

len = zeros(sample, length(nn)); % array to record the results

for n = 1:length(nn)                     % For each number of pts to generate
    numpts = nn(n);
    for i = 1:sample                     % For each round of sampling,
        p = round(rand(numpts,1) * x);   % generate 'numpts' random points.
        if any(p>pos)                    % If any are to the right of the barrier,
            pright = min(p(p>pos));      % pick the smallest.
        else
            pright = len2;
        end
        if any(p<pos)                    % If any are to the left of the barrier,
            pleft = max(p(p<pos));       % pick the largest.
        else
            pleft = len1;
        end
        len(i,n) = pright - pleft;       % Record the length of the interval.
    end
end

我当前的问题:我想让这个更复杂。例如,我希望能够在每一轮中使用多于一个随机数。具体来说,我想将此与具有不同均值的泊松分布联系起来:

% Create poisson distributions for λ = 1:12
range = 0:20;
for l=1:12;
  y = poisspdf(range,l);
  dist(:,l) = y;
end

由此,我想为每个λ取1000个样本,但在每轮1000个样本中,所有1000个样本的随机数计数不再相同。相反,它取决于泊松分布。例如,在平均值1内,概率为:

0 - 0.3678
1 - 0.3678
2 - 0.1839
3 - 0.0613
4 - 0.0153
5 - 0.0030
6 - 0.0005
7 - 0.0001
8 - 0.0000
9 - 0.0000
10 - 0.0000
11 - 0.0000
12 - 0.0000

因此,对于第一轮1000个样本,其中367个将执行仅生成1个数字,367个执行生成2个数字,183个执行生成3个数字,依此类推。然后程序将使用从平均值2获得的新值重复此操作,依此类推。然后,我想简单地将所有片段大小(pright-pleft)收集到一个矩阵列中 - 每个λ值都有一列。

我知道我可以这样做:

amount = dist*sample

将泊松分布乘以样本大小以获得它应该做的每个数字生成的数量 - 但是我真的坚持如何将其合并到for循环中并改变代码以满足处理这个新的问题。我也不确定如何读取矩阵上的列以使用每个概率值来确定它应该执行的每种类型的RNG的数量。

非常感谢任何帮助,

安娜。

1 个答案:

答案 0 :(得分:1)

如果您有统计工具箱,则可以使用random从已知的pdf对象生成随机变量向量。更好的是,跳过PDF步骤并使用poissrnd生成随机变量。将值四舍五入为最接近的整数,并按原样调用rand。在你的循环中,只需迭代生成的泊松分布随机数矢量。

示例:

x = 100;       % length of the grid
pos = 50;      % position of the barrier
len1 = 0;      % left edge of the grid
len2 = x;      % right edge of the grid

sample = 1000; % number of samples to make
lambda = 1:12;  % lambdas

Rrnd = round(poissrnd(repmat(lambda,sample,1)));
len = zeros(size(Rrnd)); % array to record the results

for n = lambda;                         % For each number of pts to generate  
    for i = 1:sample                     % For each round of sampling,
        numpts = Rrnd(i,n);
        p = round(rand(numpts,1) * x);   % generate 'numpts' random points.
        len(i,n) = min([p(p>pos);len2]) - max([p(p<pos);len1]); % Record the length
    end
end