# Shuffle matrix elements

조회 수: 76 (최근 30일)
Raviteja 2011년 11월 3일
Hey guys, I want to shuffle a 3x3 matrix (which consist elements within 1:9 unrepeated). So that I have written a very strange code.
>>X=perms(1:9);
Execute above line once.
Then execute below line how many shuffled matrices you want.
>>SMx=reshape(X(randi(size(X,1)),:),3,3)
Is there any better way to do this?

댓글을 달려면 로그인하십시오.

### 채택된 답변

Jan 2011년 11월 3일
SMx = reshape(randperm(9), 3, 3);
If you have Matlab 2011b, use "randperm(9, 9)" instead: It uses the Fisher-Yates-Shuffle, which is much faster. And if you struggle with large arrays, this is even faster: FEX: Shuffle.

댓글을 달려면 로그인하십시오.

### 추가 답변 (2개)

Fangjun Jiang 2011년 11월 3일
I believe it means to be randperm(), not perms().
OrigData=magic(3);
X=randperm(numel(OrigData));
ShuffledData=reshape(OrigData(X),size(OrigData))
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Jan 2011년 11월 3일
PERMS is correct: Raviteja produces *all* permutations at first and chooses a specific one afterwards. This needs a lot of memory...

댓글을 달려면 로그인하십시오.

A function file as I did with out randperm()
function W = randomize(A)
[m,n] = size(A);
E = A(:);
W(1) = E(1);
E(1) =[];
N = m*n;
while length(E) > 0
K = length(W);
RandInd = randi(length(E),1);
for j = 1: K
P(j) = E(RandInd) ~= W(j);
end
if all(P)
W =[W,E(RandInd)];
E(RandInd) =[];
end
end
W = reshape(W,m,n);

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by