How can I use randperm.m to convert one matrix to another?
2 views (last 30 days)
Show older comments
Hi,
I want to take an m x n matrix called A, generate a random permutation of each row, and then place that random permutation into a new matrix called B. I want to use randperm to do this and I want the code to do the entire matrix so that I end up with a new m x n matrix where each row has been effectively randomly reordered. So far, I have only be able to generate the first row of matrix B using code like this:
matrixB = matrixA( randperm(length(matrixX)) );
What is the best way to write the code so that it does ALL of the rows?
0 Comments
Answers (3)
Azzi Abdelmalek
on 24 Oct 2012
Edited: Azzi Abdelmalek
on 24 Oct 2012
A=magic(6) % example
[n,m]=size(A)
B=cell2mat(arrayfun(@(x) A(x,randperm(m)),(1:n)','un',0))
0 Comments
Sean de Wolski
on 24 Oct 2012
SO stick it in a for-loop, this will be the best way to do this unless you really want to be fancy, in which case I think this will still be the best way to do this:
sz = size(matrix(A));
matrixB = zeros(sz);
for ii = 1:sz(1)
matrixB(ii,:) = matrixA(ii,randperm(sz(2)));
end
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!