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?

답변 (3개)

Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 24일
편집: Azzi Abdelmalek 2012년 10월 24일
A=magic(6) % example
[n,m]=size(A)
B=cell2mat(arrayfun(@(x) A(x,randperm(m)),(1:n)','un',0))
Sean de Wolski
Sean de Wolski 2012년 10월 24일
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 2012년 10월 24일
편집: Matt Fig 2012년 10월 24일
% 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).'

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2012년 10월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by