image thumbnail

nchoosecrit(S, FUN)

version 2.0.0.0 (4.06 KB) by Jos (10584)
returns those subsets (= combinations of elements of a set) that fulfill a specific criterion

760 Downloads

Updated 06 Feb 2018

View License

W = nchoosecrit(S, FUN) returns those combinations of one or more element of the set S (called a subset) that fulfill a specific criterion. This criterion is specified by the function FUN. FUN is a function handle to a function that takes one input argument and returns a logical scalar value.
W will be cell array of row vectors. Each cell of W holds one of the combinations C of S for which FH(C) is true.

[W, IX] = nchoosecrit(S, FUN) also returns the indices, such that S(IX{k}) equals W{k}.
Maximally, there are 2^N-1 possible subsets of S (N being the number of elements of S). This number therefore grows rapidly with increasing N. W is a selection of those subsets.

S can be a cell array, and each cell of W will then contain a cell array.

Examples:
% find the subsets that sum op to 6
nchoosecrit([1 2 3 4 5 6], @(x) sum(x)==6)
% -> { [1 2 3], [2 4], [1 5], [6]}

% find subgroups of 4 or more people that contain either James or Bob,
% but not both!
S = {'Bob' 'Tom' 'Joe' 'Bill' 'James', 'Henry'} ; % the whole group
% criterion 1:
fh1 = @(x) numel(x) >= 4 ;
% criterion 2
fhname = @(x,y) any(strncmp(y,x,numel(y))) ;
fh2 = @(x) xor(fhname(x,'James'), fhname(x,'Bob')) ;
% the 2 criterions combined:
fhcomb = @(x) fh1(x) && fh2(x) ;
[W, IX] = nchoosecrit(S, fhcomb)
S(IX{2}), W{2} % check

Notes:
- If S contain non-unique elements (e.g. S = [1 1 2]), nchoosecrit will
return non-unique cells. In other words, nchoosecrit treats all elements
of S as being unique. One could use nchoosecrit(UNIQUE(S)) to avoid that.
- The output is the same as
Wtemp = nchoose(S) ; W = Wtemp(cellfun(Wtemp, fh)) ;
but does not create the (possible very large) temporary array Wtemp.

See also nchoosek, perms
nchoose, permn, allcomb on the file Exchange

Cite As

Jos (10584) (2021). nchoosecrit(S, FUN) (https://www.mathworks.com/matlabcentral/fileexchange/40301-nchoosecrit-s-fun), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2017b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: nchoose

Community Treasure Hunt

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

Start Hunting!