How can I use randperm.m to convert one matrix to another?
Afficher commentaires plus anciens
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?
Réponses (3)
Azzi Abdelmalek
le 24 Oct 2012
Modifié(e) : Azzi Abdelmalek
le 24 Oct 2012
A=magic(6) % example
[n,m]=size(A)
B=cell2mat(arrayfun(@(x) A(x,randperm(m)),(1:n)','un',0))
Sean de Wolski
le 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
% 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).'
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!