matthiasm@8: function [T, bitv] = subsets(S, U, L, sorted, N) matthiasm@8: % SUBSETS Create a set of all the subsets of S which have cardinality <= U and >= L matthiasm@8: % T = subsets(S, U, L) matthiasm@8: % U defaults to length(S), L defaults to 0. matthiasm@8: % So subsets(S) generates the powerset of S. matthiasm@8: % matthiasm@8: % Example: matthiasm@8: % T = subsets(1:4, 2, 1) matthiasm@8: % T{:} = 1, 2, [1 2], 3, [1 3], [2 3], 4, [1 4], [2 4], [3 4] matthiasm@8: % matthiasm@8: % T = subsets(S, U, L, sorted) matthiasm@8: % If sorted=1, return the subsets in increasing size matthiasm@8: % matthiasm@8: % Example: matthiasm@8: % T = subsets(1:4, 2, 1, 1) matthiasm@8: % T{:} = 1, 2, 3, 4, [1 2], [1 3], [2 3], [1 4], [2 4], [3 4] matthiasm@8: % matthiasm@8: % [T, bitv] = subsets(S, U, L, sorted, N) matthiasm@8: % Row i of bitv is a bit vector representation of T{i}, matthiasm@8: % where bitv has N columns (representing 1:N). matthiasm@8: % N defaults to max(S). matthiasm@8: % matthiasm@8: % Example: matthiasm@8: % [T,bitv] = subsets(2:4, 2^3, 0, 0, 5) matthiasm@8: % T{:} = [], 2, 3, [2 3], 4, [2 4], [3 4], [2 3 4] matthiasm@8: % bitv= matthiasm@8: % 0 0 0 0 0 matthiasm@8: % 0 1 0 0 0 matthiasm@8: % 0 0 1 0 0 matthiasm@8: % 0 1 1 0 0 matthiasm@8: % 0 0 0 1 0 matthiasm@8: % 0 1 0 1 0 matthiasm@8: % 0 0 1 1 0 matthiasm@8: % 0 1 1 1 0 matthiasm@8: matthiasm@8: n = length(S); matthiasm@8: matthiasm@8: if nargin < 2, U = n; end matthiasm@8: if nargin < 3, L = 0; end matthiasm@8: if nargin < 4, sorted = 0; end matthiasm@8: if nargin < 5, N = max(S); end matthiasm@8: matthiasm@8: bits = ind2subv(2*ones(1,n), 1:2^n)-1; matthiasm@8: sm = sum(bits,2); matthiasm@8: masks = bits((sm <= U) & (sm >= L), :); matthiasm@8: m = size(masks, 1); matthiasm@8: T = cell(1, m); matthiasm@8: for i=1:m matthiasm@8: s = S(find(masks(i,:))); matthiasm@8: T{i} = s; matthiasm@8: end matthiasm@8: matthiasm@8: if sorted matthiasm@8: T = sortcell(T); matthiasm@8: end matthiasm@8: matthiasm@8: bitv = zeros(m, N); matthiasm@8: bitv(:, S) = masks;