Combinatoral Iteration in Matlab

Often we need a to write a program that iterates over all combinations of k elements from some set (elements chosen without replacement). It isn't obvious how to efficiently traverse through all these sets, although if bitwise arithmetic is readily available one can use Gosper's Hack. This kind of problem comes up quite commonly in Matlab with all its use in scientific prototyping, but the necessary bitwise operations for Gosper's hack aren't easily accessible here without special toolboxes. I have written an iterator for Matlab that works around this nuisance:

gosper.m.

A few improvements could be useful:

On the other hand, this code is probably robust enough for most applications. My old laptop finishes over 7000 iterations per second on sets of size 100 which (perhaps alarmingly) seems decent for Matlab.

Comments