# How to shuffle two column array?

조회 수: 14 (최근 30일)
aburl . 2018년 9월 14일
댓글: Greg . 2018년 9월 15일
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 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);
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표시 이전 댓글 수: 1숨기기 이전 댓글 수: 1
Greg 2018년 9월 15일
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!

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

### 카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

R2015a

### Community Treasure Hunt

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

Start Hunting!