Obtain all integer partitions for a given integer

조회 수: 29 (최근 30일)
Farid Salazar Wong
Farid Salazar Wong 2015년 7월 1일
편집: Bruno Luong 2020년 9월 19일
Is there a way to compute all integer partitions for a given integer?
For example n=4
we have
4+ 0 + 0 +0
3+ 1 + 0 +0
2+ 2 + 0 +0
2+ 1 + 1 +0
1+ 1 + 1 +1
I would like to obtain a matrix
[4, 0, 0, 0;
3, 1, 0, 0;
2, 2, 0, 0;
2, 1, 1, 0;
1, 1, 1, 1]

답변 (2개)

Matt J
Matt J 2015년 7월 1일
This seems to do it. It uses NSUMK ( Download ). For example,
[~,x] = nsumk(4,4);
result=flipud(unique(sort(x,2,'descend'),'rows'))
leads to,
result =
4 0 0 0
3 1 0 0
2 2 0 0
2 1 1 0
1 1 1 1
  댓글 수: 5
Michael Vaughan
Michael Vaughan 2020년 9월 19일
I'm copying and pasting what the original poster typed into the command prompt, that is:
[~,x] = nsumk(4,4);
result=flipud(unique(sort(x,2,'descend'),'rows'))
and i'm not getting any good output. It's getting an error
Error: File: nsumk.m Line: 11 Column: 53
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To
construct matrices, use brackets instead of parentheses.
Walter Roberson
Walter Roberson 2020년 9월 19일
Line 11 of nsumk.m is a comment, so that does not make any sense
% is a natural way to list coefficients of polynomials in N variables of degree K.
unless you also provided your own nsumk.m ?
Also, which MATLAB version are you using?

댓글을 달려면 로그인하십시오.


Bruno Luong
Bruno Luong 2020년 9월 19일
편집: Bruno Luong 2020년 9월 19일
I wrote a short function that doesn't need to post-proceesed with UNIQUE (wast of time and memory) when using with NSUMK or allvL1 (order matter)
function v = Partition(n, lgt)
% v = Partition(n)
% INPUT
% n: non negative integer
% lgt: optional non negative integer
% OUTPUT:
% v: (m x lgt) non-negative integer array such as sum(v,2)==n
% each row of v is descending sorted
% v contains all possible combinations
% m = P(n) in case lgt == n, where P is the partition function
% v is (dictionnary) sorted
% Algorithm:
% Recursive
% Example:
% >> Partition(5)
%
% ans =
%
% 5 0 0 0 0
% 4 1 0 0 0
% 3 2 0 0 0
% 3 1 1 0 0
% 2 2 1 0 0
% 2 1 1 1 0
% 1 1 1 1 1
if nargin < 2
lgt = n;
end
v = PartR(lgt+1, n, Inf);
end % Partition
%% Recursive engine of integer partition
function v = PartR(n, L1, head)
rcall = isfinite(head);
if rcall
L1 = L1-head;
end
if n <= 2
if ~rcall
v = L1;
elseif head >= L1
v = [head, L1];
else
v = zeros(0, n, class(L1));
end
else % recursive call
j = min(L1,head):-1:0;
v = arrayfun(@(j) PartR(n-1, L1, j), j(:), 'UniformOutput', false);
v = cat(1,v{:});
if rcall
v = [head+zeros([size(v,1),1], class(head)), v];
end
end
end % PartR

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by