MATLAB randomly rearranges columns differently

I have a very large matrix A with N rows and columns M. I want to basically do the following operation

for k = 1:N A(k,:) = A(k,randperm(M)); end 

but fast and efficient. (Both M and N are very large, and this is just an inner loop in a more massive outer loop.)

More context: I'm trying to implement a permutation test for a correlation matrix ( http://en.wikipedia.org/wiki/Resampling_%28statistics%29 ). My data is very large and I am very impatient. If anyone knows a quick way to implement such a test, I would also appreciate your input!

Do I have any hope of avoiding this in a loop?

Sorry if this has already been asked. Thanks!

+3
source share
1 answer

If you type open randperm (at least in Matlab R2010b), you will see that its output p for input M is

 [~, p] = sort(rand(1,M)); 

So, to vectorize this for strings N ,

 [~, P] = sort(rand(N,M), 2); 

So generate p and use linear indexing in A :

 [~, P] = sort(rand(N,M), 2); A = A(bsxfun(@plus, (1:N).', (P-1)*N)); 

Example: given

 N = 3; M = 4; A = [ 1 2 3 4 5 6 7 8 9 10 11 12 ]; 

one (random) result

 A = 2 3 1 4 7 5 8 6 9 11 12 10 
+4
source

All Articles