首页 > 解决方案 > 这个随机采样循环可以向量化以进行优化吗?

问题描述

我试图在下面的代码中找到如何矢量化 FOR 循环:

h=load('water-column');                 % load file 
perm=5;                         % make 10000 permutation
n_1=5;                            % number of random sample
dm_ale=zeros(1,perm);               % create a vector 
sz=length(h);                     % count size of matrix data    
for k=1:perm                      % making loop for the permutation
    i_1=randsample(sz,n_1);      
    x_3=h(i_1);            
    x_4=h(setdiff(1:sz,i_1));    
    dm_ale(k)=abs(mean(x_3)-mean(x_4)); % calculate difference of mean for each permutation
end

至于文件输入,我有这样的东西(只是一个示例,真实文件包含更多数据):

   3792.615000000000
   3792.625000000000
   3792.634000000000
   3792.640000000000
   3792.647000000000
   3792.654000000000
   3792.662000000000
   3792.668000000000
   3792.673000000000

我不知道可以将增量放在向量化语句中的哪个位置。是否可以将其矢量化?

正如 Cris Luengo(抱歉,我不知道如何标记用户)提出的代码,我遇到了一个错误:

error: randsample: The input k must be a non-negative integer. Sampling without replacement needs k <= n.
error: called from
    randsample at line 46 column 5
    random_sampling at line 8 column 5

random_sampling代码的名称在哪里。

最初我需要perm=10000(进行稳健的随机抽样测试)和n_1=600(需要人口数,以便我的测试可以工作)。即使我遵守条件,上面的代码似乎也不起作用:n_1^2<< perm。我假设错误是由于n_1perm. 还有其他线索吗?我正在考虑增加perm

标签: for-loopvectorizationoctavepermutation

解决方案


您不能使用randsample一次生成多个随机抽样(或者从阅读文档中看来)。如果h足够大,并且perm足够n_1小(sz>> perm*n_1),那么您可以使用元素创建随机抽样perm*n_1,然后将其划分为perm集合。这可能大致可以,但与您现在正在做的不完全相同。

然后,您的代码将如下所示(使用 Geoffrey Brent在评论中建议的简化):

h = load('col-deau');
perm = 5;
n_1 = 5;
sz = numel(h);  % numel is always better than length if you use one index h(i_1) rather than two h(i_1,1)
sum_h = sum(h)
i_1 = randsample(sz, n_1 * perm);
i_1 = reshape(i_1, n_1, perm);
x_3 = h(i_1);                    % x_3 has the same size as i_1
x_3 = sum(x_3, 1);               % sum over columns, x_3 has perm elements now
x_4 = sum_h - x_3;
dm_ale = abs(x_3 / n_1 - x_4 / (sz-n_1));

如果perm也很大(如注释中所示),但n_1仍然很小,您可以使用带替换的随机抽样来近似此值(使用小n_1,您在一组中有重复元素的机会很小):

i_1 = randsample(sz, n_1 * perm, true);

推荐阅读