How can I use randperm.m to convert one matrix to another?

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?

Respuestas (3)

Azzi Abdelmalek
Azzi Abdelmalek el 24 de Oct. de 2012
Editada: Azzi Abdelmalek el 24 de Oct. de 2012
A=magic(6) % example
[n,m]=size(A)
B=cell2mat(arrayfun(@(x) A(x,randperm(m)),(1:n)','un',0))
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
Matt Fig
Matt Fig el 24 de Oct. de 2012
Editada: Matt Fig el 24 de Oct. de 2012
% Say we are given this:
A = randi(100,4,8);
% Now the method:
[m,n] = size(A);
B = bsxfun(@(x,y) A(y,randperm(x)).',n*ones(n,1),1:m).'

Categorías

Más información sobre Mathematics en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by