From 55862aa014f338789aa138831bf778d295c0f3aa Mon Sep 17 00:00:00 2001 From: Saad Jbabdi <saad@fmrib.ox.ac.uk> Date: Tue, 22 Aug 2006 12:41:27 +0000 Subject: [PATCH] added a permutation function --- miscprob.cc | 29 +++++++++++++++++++++++++++++ miscprob.h | 3 +++ 2 files changed, 32 insertions(+) diff --git a/miscprob.cc b/miscprob.cc index 89f7623..00b08a3 100644 --- a/miscprob.cc +++ b/miscprob.cc @@ -145,4 +145,33 @@ ReturnMatrix mvnrnd(const RowVector& mu, const SymmetricMatrix& covar, int nsamp return mvn.next(nsamp); } +ReturnMatrix perms(const int n){ + if(n<=1){ + Matrix P(1,1); + P << n; + P.Release(); + return P; + } + Matrix Q = perms(n-1); // recursive calls + int m = Q.Nrows(); + Matrix P(n*m,n); + for(int i=1;i<=m;i++){ + P(i,1)=n; + for(int j=1;j<=Q.Ncols();j++) + P(i,j+1)=Q(i,j); + } + for(int i=n-1;i>=1;i--){ + int jj=1; + for(int j=(n-i)*m+1;j<=(n-i+1)*m;j++){ + P(j,1)=i; + for(int k=1;k<=n-1;k++){ + P(j,k+1)= (Q(jj,k)==i) ? n : Q(jj,k); + } + jj++; + } + } + P.Release(); + return P; +} + } diff --git a/miscprob.h b/miscprob.h index 26c2e04..f0fb80b 100644 --- a/miscprob.h +++ b/miscprob.h @@ -41,6 +41,9 @@ namespace MISCMATHS { ReturnMatrix gammacdf(const RowVector& vals, const float mu = 0, const float var = 1); + // returns n! * n matrix of all possible permutations + ReturnMatrix perms(const int n); + class Mvnormrandm { -- GitLab