# How to shuffle two column array?

23 views (last 30 days)
aburl on 14 Sep 2018
Commented: Greg on 15 Sep 2018
Hello,
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;
Two problems.
• 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 on 14 Sep 2018
Edited: Greg on 14 Sep 2018
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);
end
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.
##### 2 CommentsShowHide 1 older comment
Greg on 15 Sep 2018
Happy to help. Can't be an expert on day 1, so start somewhere. The first approach that makes sense and gives acceptable results - that's a great place to start.
On that note, I'm not coming up with any better approach to (my understanding of) your problem. So kudos there!

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2015a

### Community Treasure Hunt

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

Start Hunting!

Translated by