如何减少这种组合计算的内存使用量?

鲍勃森·杜格纳特

我有以下程序:

m = 4;
N = 3;

a = [ones(N+m-1,1)' zeros(m,1)']; % creates an array with specified number of 0's and 1's
b = perms(a);
c = unique(b,'rows'); % with these last two lines, I find all possible combinations

% the rest is probably not relevant for the question

d = [ones(length(c),1) c ones(length(c),1)]; 

a_powers = zeros(length(d(:,1)),1);
for i = 1:length(d(:,1))         
    a_powers(i) = nnz(diff(d(i,:))==0);
end

[n_terms,which_power]=hist(a_powers',unique(a_powers'));

但是,当我尝试m = 5和N = 2时,我的计算机内存不足,并出现以下错误:

  Out of memory. Type HELP MEMORY for your options.

  Error in perms>permsr (line 53)
  P = V(P);

  Error in perms (line 26)
  P = permsr(V);

我以为我可以使用nchoosek()或combnk(),但是它们并没有满足我的要求(在数组中获得给定数目的1和0的所有可能的不同组合)。

我该怎么做才能优化我的程序?

谢谢!

烧杯

nchoosek是您要寻找的。对于结果中的每一行,nchoosek将给出其中的列号。该行的其余列将为零。

m = 4;
N = 3;

numberOnes = N+m-1;   % This is `k`
patternLength = numberOnes + m;   % This is `n`
patternCount = nchoosek(patternLength, numberOnes);   % Total number of combinations
bitPatterns = zeros(patternCount, patternLength);     % Preallocate output matrix

patterns = nchoosek(1:patternLength, numberOnes);     % Gives us the column numbers of the 1's
bitLocations = bsxfun(@(r,c) sub2ind(size(bitPatterns), r, c),   % Convert the column numbers in to array indices
                                [1:patternCount]', patterns);    %   for each row in `patterns`
bitPatterns(bitLocations) = 1;   % Set all of the bitLocations indices to 1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章