V_PERMUTES All N! permutations of 1:N + signatures [P,S]=(N) The output P is a matrix of size (N!,N) where each row contains a permutation of the numbers 1:N. The rows are in lexically sorted order. To permute the elements of an arbitrary vector V use V(PERMUTES(LENGTH(V))).
0001 function [p,s]=v_permutes(n) 0002 %V_PERMUTES All N! permutations of 1:N + signatures [P,S]=(N) 0003 % The output P is a matrix of size (N!,N) where each row 0004 % contains a permutation of the numbers 1:N. The rows are in 0005 % lexically sorted order. 0006 % 0007 % To permute the elements of an arbitrary vector V use 0008 % V(PERMUTES(LENGTH(V))). 0009 0010 % PERMUTES(N) is the same as SORTROWS(PERMS(1:N)) but much faster. 0011 0012 % Thanks to Peter J Acklam for several improvements. 0013 0014 % Copyright (c) 1998 Mike Brookes, mike.brookes@ic.ac.uk 0015 % Version: $Id: v_permutes.m 10865 2018-09-21 17:22:45Z dmb $ 0016 % 0017 % VOICEBOX is a MATLAB toolbox for speech processing. 0018 % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html 0019 % 0020 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 0021 % This program is free software; you can redistribute it and/or modify 0022 % it under the terms of the GNU General Public License as published by 0023 % the Free Software Foundation; either version 2 of the License, or 0024 % (at your option) any later version. 0025 % 0026 % This program is distributed in the hope that it will be useful, 0027 % but WITHOUT ANY WARRANTY; without even the implied warranty of 0028 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 0029 % GNU General Public License for more details. 0030 % 0031 % You can obtain a copy of the GNU General Public License from 0032 % http://www.gnu.org/copyleft/gpl.html or by writing to 0033 % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. 0034 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 0035 0036 p=1; 0037 m=1; 0038 if n>1 0039 for a=2:n 0040 q=zeros(a*m,a); 0041 r=2:a+1; 0042 ix=1:m; 0043 for b=1:a 0044 q(ix,1)=b; 0045 q(ix,2:a)=r(p); 0046 r(b)=b; 0047 ix=ix+m; 0048 end 0049 m=m*a; 0050 p=q; 0051 end 0052 end 0053 if nargout>1 s=1-2*rem(fix((1:m)'/2),2); end