How to shuffle two column array?
23 ビュー (過去 30 日間)
I'm trying to shuffle both the columns and rows of a two column array, but I'm running into a problem with the randomization of the columns. I want to preserve the pairs in the columns.
Here's a shortened version of the way I've written things:
A = nchoosek(1:4,2);
rowRand = randperm(size(A,1));
B = A(rowRand,:);
colRand = randperm(size(A,2));
C = B(:,colRand);
check = B == C;
- When B is randomized, the number in the first column is always smaller than the number in the second column. While that's okay ~50% of the time, that's what I'm trying to change!
- check is often true, which while I understand why it's happening, is problematic (and related to the above bullet).
Is there a way to do this without a loop? If I were to implement a loop, what would be the best way to go? I'm imagining something using a counter from the length of A... but I'm not sure how to randomize successive rows. Luckily, the array isn't very big in the actual program (usually 28x2).
Greg 2018 年 9 月 14 日
編集済み: Greg 2018 年 9 月 14 日
The values of B being in ascending order along a row has nothing to do with the randomization. It is because A is in order - because that is how nchoosek works. Does your actual use case involve the application of nchoosek to generate A? If no, your code should work.
In either case, I suspect you want to randomize the columns on a per-row basis, rather than an array-wide column permutation. For that, a loop would be pretty simple:
[nrow,ncol] = size(A);
C = B;
for irow = 1:nrow
colRand = randperm(ncol);
C(irow,:) = B(irow,colRand);
I'm not seeing a way to do it without a loop right off, but one probably exists. Sometimes the non-loop methods aren't worth the hassle - they can be obfuscated or complicated, and occasionally even slower.