Vec partitions
From QETLAB
vec_partitions | |
Produces all possible partitions of a vector | |
Other toolboxes required | none |
---|---|
Function category | Helper functions |
This is a helper function that only exists to aid other functions in QETLAB. If you are an end-user of QETLAB, you likely will never have a reason to use this function. |
vec_partitions is a function that returns all partitions a given vector into a specified number of parts. Note that, for this function, the order of the parts does matter, but the order of the elements within the parts does not matter (for example, when partitioning the vector [1,2,3,4], the partition {[1],[2,3,4]} is the same as {[1],[3,2,4]}, but distinct from {[2,3,4],[1]}).
Syntax
- PT = vec_partitions(V,P)
- PT = vec_partitions(V,P,SZ)
Argument descriptions
- V: A vector to be partitioned.
- P: A positive integer: the number of parts to partition P into.
- SZ (optional, default [1,1,...,1]): A vector such that only the partitions with the property that the j-th part contains at least SZ(j) elements (for all j) are returned.
Examples
The following code generates all 14 partitions of the vector [1,2,3,4] into two parts. It then displays two of those partitions (the first and sixth).
Source code
Click on "expand" to the right to view the MATLAB source code for this function.
%% VEC_PARTITIONS Produces all possible partitions of a vector
%
% PT = vec_partitions(V,P,SZ) computes all partitions of the vector V
% into P parts. PT is a cell, each of whose entries is a 1-by-P cell
% containing the P different parts.
%
% This function has one optional argument:
% SZ (default [1,1,...,1])
%
% PT = vec_partitions(V,P,SZ) computes all partitions of the vector V
% into P parts, with the restriction that, for all j, the j-th part must
% have at least SZ(j) elements.
%
% URL: http://www.qetlab.com/vec_partitions
% requires: opt_args.m
% author: Nathaniel Johnston (nathaniel@njohnston.ca)
% package: QETLAB
% last updated: October 18, 2014
function pt = vec_partitions(v,p,varargin)
% set optional argument defaults: sz = [1,1,...,1]
[sz] = opt_args({ ones(1,p) },varargin{:});
if(p > 1) % if p > 1 then we still have work to do
pt = cell(0);
ub = length(v) - sum(sz(2:end));
for jj = sz(1):ub
tpt = nchoosek(v,jj);
for kk = 1:size(tpt,1) % recurse through the other parties
tpt2 = vec_partitions(setdiff(v,tpt(kk,:)),p-1,sz(2:end));
for ll = 1:length(tpt2)
pt{end+1} = {tpt(kk,:), tpt2{ll}{:}};
end
end
end
else % we are on the last party: only one option left
pt{1}{1} = v;
end