How to sort the elements of a matrix in a random order

조회 수: 3 (최근 30일)
Chimezie Umezie
Chimezie Umezie 2012년 8월 28일
I have three matrix
A=[4,5,8,1,6,3]', B =[1,2,3,7,9,6]' and C=[3,1,2,4,7,9]'
and I want to generate X=[A B C] such that each element in A,B,C is randomly placed. I amusing Matlab 2007b
  댓글 수: 2
Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 28일
each element in A,B,C is randomly placed before or after concatenation?
Chimezie Umezie
Chimezie Umezie 2012년 8월 28일
before concatenation. Thanks

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

채택된 답변

Sean de Wolski
Sean de Wolski 2012년 8월 28일
편집: Sean de Wolski 2012년 8월 28일
So you want each column to be sorted randomly but to still be in the column it came from?
A=[4,5,8,1,6,3]';
B=[1,2,3,7,9,6]';
C=[3,1,2,4,7,9]';
ABC = [A B C]; %concatenate
[~,idx] = sort(rand(size(ABC))); %random indexes
ABCrand = ABC(bsxfun(@plus,idx,0:size(ABC,1):(numel(ABC)-1))) %keep columns aligned
If you don't care about elements staying in their columns, just use randperm. Of course you could always use a for-loop with randperm above, but I won't miss any opportunity to insert a bsxfun somewhere :)
  댓글 수: 2
Chimezie Umezie
Chimezie Umezie 2012년 8월 28일
편집: Chimezie Umezie 2012년 8월 28일
I am getting the following error message: ??? [~,idx] = sort(rand(size(ABC))) | Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
I am using Matlab 7.5.0
Sean de Wolski
Sean de Wolski 2012년 8월 28일
If you are on 2007b then you probably need a junk value instead of a '~'
[junk,idx] = sort(rand(size(ABC))); %random indexes

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

추가 답변 (3개)

Matlabbey
Matlabbey 2012년 8월 28일
maybe you could try making a new random matrix and sorting by those values.

Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 28일
편집: Azzi Abdelmalek 2012년 8월 28일
A=[4,5,8,1,6,3]', B =[1,2,3,7,9,6]', C=[3,1,2,4,7,9]'
nA=length(A);
a1=perms(1:nA);nA1=size(a1,1);
res=[A(a1(round(nA1*rand(1,1)),:)); B(a1(round(nA1*rand(1,1)),:)); C(a1(round(nA1*rand(1,1)),:))]
  댓글 수: 2
Chimezie Umezie
Chimezie Umezie 2012년 8월 28일
편집: Chimezie Umezie 2012년 8월 28일
I am getting the following error message when I used your solution:
"??? Undefined function or method 'randi' for input arguments of type 'double'." My Matlab version is 7.5.0
Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 28일
replace randi with round(nA1*rand(1,1))

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


Andrei Bobrov
Andrei Bobrov 2012년 8월 28일
abc = [A,B,C]
[~,idx] = sort(rand(size(abc)))
out = abc(sub2ind(size(abc),idx,ones(size(abc,1),1)*(1:size(abc,2))));

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by