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

时间:2016-08-27 15:22:26

标签: matlab memory-management

我有以下程序:

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的所有可能不同的组合)。

我可以做些什么来优化我的计划?

谢谢!

1 个答案:

答案 0 :(得分:2)

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