2016-08-27 2 views
0

나는 다음과 같은 프로그램이 있습니다이 조합기 계산에서 어떻게 메모리 사용을 줄일 수 있습니까?

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()하지만 그들은 원하는 모든 것을 할 수 없었습니다. 배열에서 주어진 수의 0과 0이 가능한 한 의 조합을 모두 얻을 수있었습니다.

내 프로그램을 최적화하려면 어떻게해야합니까?

감사합니다!

+0

긴 배열을 사용하면'perms'의 크기가 오히려 빠르므로 배열에 10 개 이상의 요소를 사용해서는 안된다는 경고 메시지가 표시됩니다. 최적화 방법은 적절한 스카이 스크레이퍼에 맞는 것보다 많은 RAM을 구입하는 것입니다. – Adriaan

+0

@Adriaan Hehe, 네, 그게 하나의 해결책입니다. 배열 요소의 모든 가능한 조합을 얻기 위해 nchoosek() 또는 combnk() 같은 것을 사용할 수 있기를 바랬지 만 모든 순열을 먼저 찾지 않고 다음 동일한 모든 행을 삭제합니다. –

+0

나는 당신이 무엇을하려고하는지 확실히 모르겠다 ... 당신은 단지 특정 비트 수가 설정된 모든 비트 문자열을 얻으려고 노력하고 있는가? 그것은 정확히'nchoosek'이하는 일입니다. – beaker

답변

2

nchoosek 당신이 찾고있는 것입니다. 결과의 각 행에 대해 nchoosek은 1의 열 수를 제공합니다. 해당 행의 나머지 열은 0입니다.

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 
관련 문제