20.08.2015 Views

MATLAB array manipulation tips and tricks

MATLAB array manipulation tips and tricks - Home - Online.no

MATLAB array manipulation tips and tricks - Home - Online.no

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 12. STATISTICS, PROBABILITY AND COMBINATORICS 3912.4 Combinations“Combinations” is what you get when you pick k elements, without replacement, from a sample ofsize n, <strong>and</strong> consider the order of the elements to be irrelevant.12.4.1 Counting combinationsThe number of ways to pick k elements, without replacement, from a sample of size n is ( nk)whichis calculated withc = nchoosek(n, k);one may also use the definition directlyk = min(k, n-k); % use symmetry propertyc = round(prod( ((n-k+1):n) ./ (1:k) ));which is safer than usingk = min(k, n-k); % use symmetry propertyc = round( prod((n-k+1):n) / prod(1:k) );which may overflow. Unfortunately, both n <strong>and</strong> k have to be scalars. If n <strong>and</strong>/or k are vectors, onemay use the fact that( n n!=k)k!(n − k)! = Γ(n + 1)Γ(k + 1)Γ(n − k + 1)<strong>and</strong> calculate this in withround(exp(gammaln(n+1) - gammaln(k+1) - gammaln(n-k+1)))where the round is just to remove any “numerical noise” that might have been introduced bygammaln <strong>and</strong> exp.12.4.2 Generating combinationsTo generate a matrix with all possible combinations of n elements taken k at a time, one mayuse the <strong>MATLAB</strong> function nchoosek. That function is rather slow compared to the choosenkfunction which is a part of Mike Brookes’ Voicebox (Speech recognition toolbox) whose homepageis http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.htmlFor the special case of generating all combinations of n elements taken 2 at a time, there is a neattrick[ x(:,2) x(:,1) ] = find(tril(ones(n), -1));12.5 Permutations12.5.1 Counting permutationsp = prod(n-k+1:n);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!