## Copyright (C) 2001 Paul Kienzle ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## c = nchoosek(n, k) ## return c = n!/(k! (n-k)!) ## A = nchoosek(v, k) ## generate all combinations of the elements of vector v taken k at a ## time, one row per combination. The resulting A has size ## nchoosek(n,k) x k, where n is the length of v. function A = nchoosek(v,k) n = length(v); if n == 1 A = prod(k+1:v)/prod(1:v-k); elseif k == 0 A = []; elseif k == 1 A = v(:); elseif k == n A = v(:)'; else A = [ v(1)*ones(prod(k:n-1)/prod(1:n-k), 1), nchoosek(v(2:n), k-1) ; \ nchoosek(v(2:n), k) ]; endif endfunction