Can I have few additional questions: 1. the "ismember" function is the most time consuming function during the computation. Is there any chance to create some faster aleternative, see for example http://www.mathworks.com/matlabcentral/newsreader/view_thread/306676#832549 2. Will be possible just count the succesful permutations, without permutation generation? 3. Will be possible to prealocate variables "p" and "q"? For bigger dimensions the expanding is slower and slower?